A Different View on Exceptions

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: