Friday, August 11, 2006

Catch me if you can ?!?

I really like the JDT's Java Exception Breakpoints: Most of the time, I'm running my code from the debugger, with breakpoints set at least on NullPointerException and ClassCastException (through Run > Add Java Exception Breakpoint). It brings my debugger exactly to those places where a problem occurs - and helps me to diagnose it right away.

But sometimes, the debugger breaks at unexpected places, like the following code I've seen the other day:
try {
} catch (NullPointerException e) {
//Nothing to execute if foo's not there yet

Apparently, the original developer's idea was that the FooManager might have a foo or not -- if it doesn't have one, then getFoo() returns null and there is nothing to execute.

Now most seasoned Java Hackers may have it in their guts that this is not good code. The younger ones might know it because Bloch writes it (Effective Java, chapter 8, Item 39: Use exceptions only for exceptional conditions; if you haven't read this book, you must read it!).

Bloch has some good arguments for avoiding exceptions instead of catching them. But using exception breakpoints, here is another just practical one - it breaks the debugger where it's not necessary, because the code does run as intended. So I've changed the code:
Foo foo = FooManager.getFoo();
if (foo!=null) {

Now that's even shorter (4 lines of code instead of 5), clearer to understand, and my Debugger won't need to get active... so in the future, I'll live with Catch me if you can't avoid me - which might have made the life of Tom Hanks easier too...

1 comment:

Anonymous said...

amen to that