Skip to content

About Java Exceptions in SE 7

November 7th, 2015 - Software(1 min)

TL;DR: JDK 7 improves on exception handling (less code, base exception class…).

Base exception class

Reflective operations exceptions now have a base class ReflectiveOperationException. This allows you to to a global catch rather than one for each exception. Now you can write:

try {
    // Some reflective stuff ...
} catch(ReflectiveOperationException e) {
    Log.e(TAG, e);
    throw e;
}

Note: Reflective operations are ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException, NoSuchMethodException.

Multi-catch

Previously, you’d had to write code like this:

try {
    // some code
} catch (IOException ioe) {
    Log.e(TAG, ioe);
} catch (NullPointerException npe) {
    Log.e(TAG, npe);
}

Now, you can write:

try {
    // some code
} catch (IOException | NullPointerException ex) {
    Log.e(TAG, ex);
}

Woo-hoo! Less lines of code!

Final catch

Normally, when you re-throw form a catch, you only re-throw the caught exception (or a sub-type). IN Java 7, you have the option to declare the catch parameter as final:

try {
    // some code
} catch (final MyException ex) {
    // some catch code
    throw ex;
}

This will actually process all exceptions of type MyException as well as all other uncaught exceptions in the block. This allows you to wrap code in a try/catch block, intercept, process and re-throw exceptions without affecting the statically determined set of exceptions thrown from the code (aka, simplified maintenance).

Note: The “statically determined set of exceptions” are exceptions that can be statically identified (i.e. defined by the throws clause on method definition.

Share on
Reddit
Linked in
Whatsapp

A little experiment: