Tips and Hints with Exceptions

We list some tips and hints here that are no best practices in the strict sense, but may prove helpful anyway.

No Generic Exceptions

A generic class must not subclass Throwable or any of its subclasses.

public class MyException <T> extends Throwable { // DOES NOT COMPILE!

The generic information is not available at runtime and catching exceptions by their generic type will not work.

try {
  ...
  }
  catch(final MyException<String> e) { // DOES NOT WORK!
  ...
  }

So keep in mind that there is no generic exception.

Exception with no Cause

Just in case you have a root cause, but the exception you want to throw does not support setting the root cause throwable in the constructor. You can use Throwable.initCause(Throwable) instead.

final Throwable t = new IllegalArgumentException("Wrong arg...");
final NullPointerException npe = new NullPointerException("NPE...");
npe.initCause(t);

Calling npe.printStackTrace() will print the following to standard error:

java.lang.NullPointerException: NPE...
  at de.smartics.exceptions.Main.main(Main.java:62)
Caused by: java.lang.IllegalArgumentException: Wrong arg...
  at de.smartics.exceptions.Main.main(Main.java:60)

Testing Serializability

It is often useful to proof that instances of a class are serializable. You may use a serialization theory as it is provided by smartics-test-utils.

The test case looks like this:

import org.junit.experimental.theories.DataPoint;
import de.smartics.util.test.theories.SerializationTheory;

public class MyExceptionSerializableTest extends SerializationTheory
{
  @DataPoint
  public static final MyException INSTANCE =
      new MyException(MyCode.ZERO, "test");
}