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
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.
Here is the syntax for writing multiple catch block >
//code . . . . .
}catch(IOException ex1){
//code . . . . .
} catch(SQLException ex2){
//code . . . . .

Here is the multi catch syntax >

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

We could separate different exceptions using pipe ( | )
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 >

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 >

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