1// syntax in java 7 Java catch multiple exceptions and rethrow exception
2try
3{
4 // code that throw exceptions 1 and 3
5}
6catch(SQLException | IOException e)
7{
8 logger.log(e);
9}
10catch(Exception e)
11{
12 logger.severe(e);
13}
1// Before java 7 - syntax Java catch multiple exceptions and rethrow exception
2try
3{
4 // code that throw exceptions 1 and 3
5}
6catch(SQLException e)
7{
8 logger.log(e);
9}
10catch(IOException e)
11{
12 logger.log(e);
13}
14catch(Exception e)
15{
16 logger.severe(e);
17}
1
2catch(IOException | SQLException ex){
3 logger.error(ex);
4 throw new MyException(ex.getMessage());
5}
6
1public class MyClass implements MyInterface {
2 public void find(int x) throws A_Exception, B_Exception{
3 ----
4 ----
5 ---
6 }
7}
1From Java 7, we can catch more than one exception with single catch block.
2This type of handling reduces the code duplication.
3
4When we catch more than one exception in single catch block ,
5catch parameter is implicity final. We cannot assign any value to catch
6parameter.
7
8Ex : catch(ArrayIndexOutOfBoundsException || ArithmeticException e){
920
10}
11
12In the example e is final we cannot assign any value or
13modify e in catch statement