Is it meaningful to declare a method to throw an exception and a subclass of this exception, e.g. IOException and FileNotFoundException?
I guess that it is used in order to handle both exceptions by a caller method differently. However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
But this doesn't look clean, Throwing both exception looks good, even caller would come to know to that this method may throw these these exceptions, so they will handle it properly
Usually not - most IDEs I know of even issue warnings for such declarations. What you can and should do is to document the different exceptions thrown in Javadoc.
Yes it is, you just need to ensure that the catch blocks are in the right order, i.e. more specific first. Catch blocks are evaluated in the order they are defined, so here
if the exception thrown is a
FileNotFoundException
, it will be caught by the firstcatch
block, otherwise it will fall to the second and dealt with as a generalIOException
. The opposite order would not work ascatch (IOException e)
would catch allIOException
s includingFileNotFoundException
. (In fact, the latter would result in a compilation error IIRC.)yes. when certain specialized exceptions can be handled correct. It is, if you handle the exceptions as follow:
Absolutely. You can still catch them separately:
So it makes no difference to what the caller can do if the method declares both - it's redundant. However, it can emphasize exceptions that you might want to consider. This could be done better in Javadoc than just the throws declaration.
Declaring, that the method may throw (more generic)
IOException
, and (more specific)FileNotFoundException
is usually a good thing - it's an additional information for people using your code later. Note that you should explicitely state in the JavaDoc, under what circumstances is each of the exceptions thrown.They will still be able to distinguish the exceptions, and handle them differently using catch constructs like this one:
Yes, it's possible to handle both if the method only throws IOException.
The best way to answer such a question is to write a test to demonstrate it and try it out. Let the JVM tell you the answer. It'll be faster than asking here.