Home > Articles > Programming > Java

Crafting Java with Test-Driven Development, Part 5: Handling Exceptions

  • Print
  • + Share This
Handling exceptions may not be exciting, but it's a crucial part of writing your application. Instead of putting it off until the "fun stuff" is done, Jeff Langr advises a head-on approach: Drive exceptions through tests, like any other production code.
From the author of

Exceptions Are the Rule

Our Texas Hold ’Em poker application is shaping up. We have a shuffled Deck from which we can deal Card objects. We also have the ability to compare cards and store them in hash-based collections.

Most developers don’t worry about exceptions until all the "happy path" coding is done. When forced to deal with the fact that an exception might get thrown, a typical reaction is for the programmer to simply log it and move on:

try {
  // ...code that could throw a checked exception...
}
catch (Exception e) {
  log(e);
}

This is the anti-pattern known as "empty catch clause," something that James Gosling says should give you a creepy feeling. Technically, the catch block isn’t empty, but as far as I’m concerned, logging an exception that is then swallowed is the same thing as doing nothing.

In many systems, log files spew constant junk to the console or to a file. Gigabytes of messages pass by quickly and remain unnoticed by many. They disappear as they scroll out of the screen buffer or as the log files roll over. Potentially valuable pieces of information just disappear—information that might be crucial in tracking down an insidious defect.

  • + Share This
  • 🔖 Save To Your Account