Is it worth declaring a method to throw an exception and subclass that exception, for example. IOException and FileNotFoundException?
Usually not - most IDEs that I know even warn of problems for such ads. What you can and should do is document the various exceptions thrown at Javadoc.
However, is it possible to handle both exceptions if the method throws only the most common ie IOException?
Yes, you just need to make sure that the catch blocks are in the correct order, i.e. more specific in the first place. The catch blocks are evaluated in the order in which they are determined, so here
try { ... } catch (FileNotFoundException e) { ... } catch (IOException e) { ... }
if the exception FileNotFoundException
is a FileNotFoundException
, it will be caught by the first catch
, otherwise it will drop to the second and will be considered as a general IOException
. The opposite order does not work, since catch (IOException e)
will catch all IOException
, including FileNotFoundException
. (In fact, the latter will result in an IIRC compilation error.)
source share