Java7 Exception Handling

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.

+7
java java-7 exception-handling
source share
3 answers

Why does the compiler report an error in the latter case, can it not be understood that FileNotFoundException is a special case of an IOException ?

Because FileNotFoundException is a subclass of IOException . In other words, the " FileNotFoundException | " part is redundant.

The reason the code below is ok ...

 } catch(FileNotFoundException e) { ... } catch(IOException e) { ... } 

... is that there is an IOException clause: if, for example, a SocketException , it passes a part of FileNotFoundException and falls into the IOException clause.

+13
source share

When an exception is detected, you arrange your catch positions from the most specific to the most general.

Consider the following hierarchy:

 class MyException extends Exception {} class MySubException extends MyException {} 

If part of your code throws MyException, another part throws MySubException, you should catch MySubException first.

 catch(MySubException e){ } catch(MyException e){ } 

This is the same as using the instanceof operator.

If you check if the instance of MySubException is an instance of MyException, the result will be true.

 mse = new MySubException(); if(mse instanceof MyException){ println("MyException"); } else if(mse instanceof MySubException){ println("MySubException"); } 

This piece of code will never throw a "MySubException".

 mse = new MySubException(); if(mse instanceof MySubException){ println("MySubException"); } else if(mse instanceof MyException){ println("MyException"); } 

This will be the correct order.

0
source share

This is because a FileNotFoundException extends an IOException, since you said that it is the same hierarchy, you cannot add them to the same catch block.

0
source share

All Articles