Difference between multiple catch block and multi catch syntax in java




In this post we will be discussing differences between multiple catch block and multi catch syntax




Difference between multiple catch block and multi catch syntax in java >


multiple catch block
multi catch syntax
1
multiple catch blocks were introduced in prior versions of Java 7 and does not provide any automatic resource management.
multi catch syntax was introduced in java 7 for improvements in multiple exception handling which helps in automatic resource management.
2
Here is the syntax for writing multiple catch block >
try{
//code . . . . .
}catch(IOException ex1){
//code . . . . .
} catch(SQLException ex2){
//code . . . . .
}      

Here is the multi catch syntax >

try{
//code . . . . .
}catch(IOException | SQLException ex){
//code . . . . .
}      

We could separate different exceptions using pipe ( | )
3
For catching IOException and SQLException we need to write two catch block like this >


with the help of multi catch syntax we can catch IOException and SQLException in one catch block using multi catch syntax like this >



4
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.

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.
Solution >
We must use only Exception to catch its subclass like this >

5
Does not provide such features.
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.


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

No comments:

Post a Comment