Catch block and Automatic Resource Management in java 7


Contents of page :
  • Features of multi catch syntax >
  • Using multi catch syntax to catch subclass and its superclass exception.

As we read in previous posts java allows us to handle multiple exceptions by using multiple catch blocks.
In that post we read Exception class handled in starting catch block must be subclass of Exception class handled in following catch blocks (otherwise we will face compilation error).
Now, java 7 has done improvements in multiple exception handling by introducing multi catch syntax which helps in automatic resource management.


Features of multi catch syntax >
  • Has improved way of catching multiple exceptions.
  • This syntax does not looks clumsy.
  • Reduces developer efforts of writing multiple catch blocks.
  • Allows us to catch more than one exception in one catch block.
  • Helps in automatic resource management.

Here is the multi catch syntax >
             try{
                 //code . . . . .
          }catch(IOException | SQLException ex){
                 //code . . . . .
          }      
We could separate different exceptions using pipe ( | )


Before java 7, for catching IOException and SQLException we were needed to write two catch block like this >


But in java 7, we can catch IOException and SQLException in one catch block using multi catch syntax like this >




Using multi catch syntax to catch subclass and its superclass exception.
When multiple catch blocks are used , first catch block could be subclass of Exception class handled in following catch blocks like this >
IOException is subclass of Exception.


But in java 7, if multi catch syntax is used to catch subclass and its superclass than compilation error will be thrown.
IOException and Exception in multi catch syntax will cause compilation error “The exception IOException is already caught by the alternative Exception.
IOException is subclass of Exception.
Solution >
We must use only Exception to catch its subclass like this >


/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */




RELATED LINKS>


EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - detailed explanation with diagrams Set-1 > Q1- Q25


EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - 30 important OUTPUT questions Set-2 > Q26- Q60


eEdit
Must read for you :