Java 7 allows us to capture multiple exceptions in the same catch statement block. This is also called multi-exception capture.
Before Java 7, we may want to do this:
The code is as follows: |
Copy code |
Try {
// Execute code that may throw 1 of the 3 exceptions below.
} Catch (SQLException e ){ Logger. log (e );
} Catch (IOException e ){ Logger. log (e );
} Catch (Exception e ){ Logger. severe (e ); } |
As shown above, SQLException and IOException are both handled in the same way, but you still need to write two independent catch statement blocks for these two exceptions.
In java 7, you can catch multiple exceptions as follows:
The code is as follows: |
Copy code |
Try {
// Execute code that may throw 1 of the 3 exceptions below.
} Catch (<strong> SQLException | IOException e </strong> ){ Logger. log (e );
} Catch (Exception e ){ Logger. severe (e ); } |
Note: The two exception names in the first catch statement block are separated by pipeline characters. Pipeline characters between two exception classes are the methods for declaring multiple exceptions in the same catch statement block.