Catching multiple exceptions in java is now very easy starting from Java 7.
Before java 7 we used to write the below code for catching multiple exceptions
1 2 3 4 5 6 7 8 9 |
try{ //Some Statements }catch(Exception1 e1 |){ //log statements }catch(Exception2 e2){ //log statements }catch(Exception3 e3){ //log statements } |
But since Java 7 we can easily club some of the exceptions,so that code redundancy can be avoided
Note that we use a vertical bar (| symbol ) to add multiple exceptions in one catch block.
1 2 3 4 5 |
try{ //Some Statements }catch(Exception1 | Exception2 | Exception3 e){ //log statements } |
Example: Catching multiple exceptions in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.kscodes.sampleproject; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class ExecptionHandling { public static void main(String[] args) { try { // get a database connection Connection connection = null; PreparedStatement ps = connection.prepareStatement("Select .... from .."); // write to a file. FileOutputStream fos = new FileOutputStream("C:\\test.txt"); } catch (IOException | SQLException e) { System.out.println("An Exception occured while writing data to file from database"); } } } |
Advantages of Caching Multiple exception
- Bytecode generated for catch block that handles multiple exception types is smaller than many catch blocks handling one exception per block.
- Code redundancy or code duplication can be avoided by catch block that handles multiple exception types.