I tried to find out the answer to this question, but did not get a satisfactory explanation. Here are some examples:
Java 7 allows us to catch several exceptions in one catch block if these exceptions are from a different hierarchy. For example:
try { // some code } catch(SQLException | FileNotFoundException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); }
But if exceptions are from the same hierarchy, we should use several catch blocks, for example:
try { // some code } catch(FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); }
But if I try to write code like the one below, the compiler complains that " FileNotFoundException has already been found as an alternative to IOException "
try { // some code } catch(FileNotFoundException | IOException e) { // compiler error e.printStackTrace(); }
Now my question is: why does the compiler report an error in the latter case, can it not be understood that FileNotFoundException is a special case of IOException ? This will save code duplication when my exception handling logic is the same.
java java-7 exception-handling
Sudhir singh
source share