In Java 7, the catch code block was upgraded to handle multiple exceptions in a single catch block. If you are capturing multiple exceptions and they contain similar code, using this feature will reduce code duplication. Here is an example to understand.
Versions prior to Java 7:
catch (IOException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
catch (SQLException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
}catch (Exception ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
}
If you use a catch block to handle multiple exceptions, you can separate them with a pipe (|) character, in which case the exception parameter variable (EX) is defined as final and therefore cannot be modified. This feature will generate fewer bytecode and reduce code redundancy.
Another upgrade is the compiler's handling of the re-throwing exception (Rethrown exceptions). This feature allows more specific exception types to be specified in the throws clause of a method declaration.
Let's take a look at a small example:
package com.journaldev.util;
public class Java7MultipleExceptions {
public static void main (String [] args) {
try {
rethrow ("abc");
} catch (FirstException | SecondException | ThirdException e) {
// The following assignment will throw an exception at compile time, because e is final
// e = new Exception ();
System.out.println (e.getMessage ());
}
}
static void rethrow (String s) throws FirstException, SecondException,
ThirdException {
try {
if (s.equals ("First"))
throw new FirstException ("First");
else if (s.equals ("Second"))
throw new SecondException ("Second");
else
throw new ThirdException ("Third");
} catch (Exception e) {
// The following assignments do not enable type checking for rethrowing exceptions. This is a new feature in Java 7.
// e = new ThirdException ();
throw e;
}
}
static class FirstException extends Exception {
public FirstException (String msg) {
super (msg);
}
}
static class SecondException extends Exception {
public SecondException (String msg) {
super (msg);
}
}
static class ThirdException extends Exception {
public ThirdException (String msg) {
super (msg);
}
}
}
As you can see in the Rethrow method, the catch block catches an exception that does not appear in the throws clause. The Java 7 compiler parses the complete try code block to check what type of exception is thrown and re-thrown from the catch block.
Note that once you change the parameters of the catch block, the compiler's analysis will not be enabled.
New JAVA 7 Features--capture multiple exceptions in a single catch block, and re-throw exceptions with the type of upgrade