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?
The throws keyword is used to declare which exceptions can be thrown from a method, while the throw keyword is used to explicitly throw an exception within a method or block of code. The throws keyword is used in a method signature and declares which exceptions can be thrown from a method.
Subclass method cannot throw the exception which is a superclass of the superclass method's exception. Subclass method can throw any unchecked or runtime exception.
To create our own exception class simply create a class as a subclass of built-in Exception class. We may create constructor in the user-defined exception class and pass a string to Exception class constructor using super(). We can use getMessage() method to access the string.
If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
Absolutely. You can still catch them separately:
try {
methodThrowingIOException();
} catch (FileNotFoundException e) {
doSomething();
} catch (IOException e) {
doSomethingElse();
}
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.
Is it meaningful to declare a method to throw an exception and a subclass of this exception, e.g. IOException and FileNotFoundException?
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.
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
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
try {
...
} catch (FileNotFoundException e) {
...
} catch (IOException e) {
...
}
if the exception thrown is a FileNotFoundException
, it will be caught by the first catch
block, otherwise it will fall to the second and dealt with as a general IOException
. The opposite order would not work as catch (IOException e)
would catch all IOException
s including FileNotFoundException
. (In fact, the latter would result in a compilation error IIRC.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With