Sunday, 29 September 2013

Enhancements in JDK 7 in handling exceptions

Catching multiple exceptions is present since jdk earlier versions but catching multiple exceptions is being introduced in jdk 1.7. Historically, catching multiple exceptions results in a catch block for each exception, with each block containing a variable with the type of that particular exception. In many cases, these catch blocks contained identical code that referenced the specified exception variable. It was difficult to write a common method to handle this duplicated code because the exception variables had different types.

try {
    Path fp = path.toRealPath(true);
} catch (NoSuchFileException x) {
    System.err.format("%s: no such file or directory%n", path);
    ...
} catch (IOException x) {
    System.err.format("%s%n", x);
    ...
}

As of JDK 7, you can catch multiple exceptions in the same catch block using the | symbol.

try {
    Path fp = path.toRealPath(true);
} catch (NoSuchFileException | IOException x) {
    System.err.format("%s: no such file or directory%n", path);
    ...
}

More precise re-throw of an exception:

Before JDK 7, re-throwing an exception in a catch block did not indicate the actual exceptions possible from the try block. Also, you could not change the type of exception thrown in the catch block without changing the method signature. As of JDK 7, the semantics for catching and throwing exceptions has been refined. If you catch an exception of some type, and do not assign to the exception variable, the compiler will copy over the checked exception type that can be thrown from the try block. It is as if you are re-throwing all the exceptions possible from the try block (provided that you don't re-assign the exception variable). For example, the following code is legal in JDK 7:

JarFile retrieve(URL url) throws IOException {
    Path temp = Files.createTempFile("jar_cache", null);
    try (InputStream in = url.openStream()) {
        Files.copy(in, temp, REPLACE_EXISTING);
        return new JarFile(temp.toFile());
    } catch (Throwable t) {
        Files.delete(temp);
        throw t;
    }

}

No comments:

Post a Comment