A Different View on Exceptions

30. January, 2009

The discussion about checked/unchecked exceptions is almost as old as Java. While we all have a point in your stance towards this, maybe we are looking at the problem from the wrong angle. Manuel Woelker wrote an article which concentrates on the receiver of the exception, the user, and how exceptions should behave to help the user: Exceptions From a User’s Perspective.

In a nutshell:

[…]the error message displayed to the user should also explain what can be done to correct the situation

Take this code:

Foo foo = cache.get( key );
Preconditions.checkNotNull( foo, "foo is null" );

This error message is wasting someone’s time. Use this instead:

Foo foo = cache.get( key );
Preconditions.checkNotNull( foo, "No Foo for %s", key );

See? That actually tells you why foo is null.

Can we do better than that? Yes, we can:

Foo foo = cache.get( key );
Preconditions.checkNotNull( foo,
    "No Foo for %s. Valid keys: %s",
    key, cache.keySet() );

As you can see, by adding just a little bit of extra information, you can prevent someone (maybe even yourself) from starting the debugger, trying to reproduce the bug and then trying to pry some useful hints of the cause from the runtime.