In Java SE 7 and later, a single catch block can handle more than one type of exception. This will avoid the code duplication.
For ex: Before Java SE 7, we would write the following code to catch multiple exceptions.
catch(IOException ex){
logger.log(ex);
throw ex;
} catch(SQLException ex){
logger.log(ex);
throw ex;
}
The same can be written as below in Java SE 7 and later which will avoid the duplicate code.
catch(IOException|SQLException ex){
logger.log(ex);
throw ex;
}
multiple exceptions are separated by vertical bar (|).
Note: If catch block handles more than one exception, then the catch parameter is implicitly final. So we can not assign any new value to the parameter (ex in the example).
For ex: Before Java SE 7, we would write the following code to catch multiple exceptions.
catch(IOException ex){
logger.log(ex);
throw ex;
} catch(SQLException ex){
logger.log(ex);
throw ex;
}
The same can be written as below in Java SE 7 and later which will avoid the duplicate code.
catch(IOException|SQLException ex){
logger.log(ex);
throw ex;
}
multiple exceptions are separated by vertical bar (|).
Note: If catch block handles more than one exception, then the catch parameter is implicitly final. So we can not assign any new value to the parameter (ex in the example).
No comments:
Post a Comment