Declare method to throw an exception and subclass of this exception

exception, java

Solution

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.

Problem

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?

Original source