Subscribe to our mailing list

* indicates required
Close

Tuesday, December 02, 2008

Exception-throwing antipatterns

Tim McCune has written an interesting article called Exception-Handling Antipatterns, at http://today.java.net (a fine place to find articles of this kind, BTW). The comments at the end of the article are every bit as stimulating as the article itself.

McCune lists a number of patterns that (I find) are very widely used (nearly universal, in fact) in Java programming, such as log-and-rethrow, catch-and-ignore, and catch-and-return-null; all considered evil by McCune. My comment is: If those are antipatterns, the mere fact that such idioms are so ubiquitous in real-world Java code says more about the language than it does about programmers.

I've always had a love-hate relationship with the exception mechanism. On the whole, I think it is overused and overrated, at least in the Java world, where people seem to get a little nutty about inventing (and sublcassing) custom exceptions and ways to handle them, when they should probably spend that energy writing better code to begin with.

1 comment:

  1. I agree that there are lots of exception-handling anti-patterns. Most of the problems arise from not simply throwing exceptions upward until you reach a method that can dispose of them properly (the root of all three anti-patterns you cite).

    But these anti-patterns are hardly universal. I know lots of Java programmers who'd never dream of catching and ignoring an exception.

    So please don't urge Sun to throw the baby out with the bath water because of under-educated programmers.

    What should a socket-based input stream do if there's a network error during a read? There can't be a test/act pattern, as it won't be guaranteed to hold between one call and the next. We could add a new integer magic-number return code (-1 means end of stream, so how about -2 for a network exception?).

    That's what you'd do in C (or at least it's what the last company I worked for did, for whom I had the pleasure of integrating Brendan Eich's SpiderMonkey implementation of JavaScript into a speech recognizer's semantic parser). Then you hack up the equivalent of Java's finally blocks to make sure you free up resources like memory or file handles. These cleanup blocks typically have multiple points of entry, so you either deal with lots of gotos or incredibly crufty if/then blocks in the code.

    ReplyDelete

Add a comment. Registration required because trolls.