In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication and make the code more readable and efficient.
Let’s understand this with an examples which shows how the multi-catch feature of java 7 works.
Code technique used before java 7:-
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); }Code technique used after java 7:-
try { // execute code that may throw 1 of the 3 exceptions below. } catch(SQLException | IOException e) { logger.log(e); } catch(Exception e) { logger.severe(e); }
Notice:- here that how the two exception class names in the firstcatch
block are separated by the pipe character|
. The pipe character between exception class names is how you declare multiple exceptions to be caught by the samecatch
clause.