Consider following multiple catch blocks – Below example contain two catch blocks having two exceptions (i.e IOException and SQLException)
Catching Multiple Exception in single catch :
Whenever try block will thrown any exception of these type then and then only we can handle the exception.
catch (IOException ex) { System.out.println("IO Exception"); throw ex; } catch (SQLException ex) { System.out.println("SQL Exception"); throw ex; }
- If in a try block we need to handle multiple exceptions then we need to write exception handler for each type of exception.
- We can combine the multiple exceptions in catch block using Pipe (|) Operator.
catch (IOException|SQLException ex) { System.out.println("Exception thrown"); throw ex; }
above single catch block can handle IO as well as SQL exceptions. So it is better to use Pipe Operator to handle multiple exceptions instead of writing individual catch block for each exception. Also Refer this oracle guide for more information.
Parameter Accepted by Catch Block is Final :
- If a catch block handles more than one exception type, then the catch parameter is implicitly final.
- In this example, the catch parameter ex is final.
- We cannot assign any values to it within the catch block.
Note :We can use Pipe (|) to catch multiple exceptions only in Java SE 7 or in higher versions.
The post Catching multiple exception types using single catch block appeared first on Learn Java Programming.