Pragmatic Exceptions

Dr. Dobb's Journal September, 2005


"Use exceptions for exceptional cases" is such a common refrain that I wonder if anyone really knows what it means. It means not using them as a part of control flow, but beyond that, the proper use of exceptions is anybody's guess and everyone's mystery.

When should you throw exceptions? Should you throw a runtime or a checked exception? Is it okay to catch a Throwable exception? Where is the best place to catch an exception? What do you do when you catch one? In general, how can you be pragmatic when it comes to exceptions?

Over the next few months, I answer some of these questions. While Java is the reference language, many of these tips are universal.

Tip #1: If In Doubt, Throw It Out

Exceptions are guilty until proven innocent. To ensure the integrity of the application (see the upcoming Tip #5 "Exceptions May Be Poisonous"), exception pitchers should also play it safe and throw exceptions out if there's any doubt. Let someone else who will know for sure take a closer look.

Throwing it out is usually the first, safest bet. At some point, higher up in the code path, there will be sufficient programmatic context to know for sure whether a contract has been broken. With less ambiguity, appropriately handling the exception becomes straightforward.

If the method signature must change, then change it if at all possible. If not, then throw an unchecked exception (in Java, a RuntimeException). This is better than blindly handling a potentially fatal state change in your application.

—Benjamin Booth benjamin.booth@gmail.com