Java Exception Handling Anti-Patterns
The following article addresses one of the hardest things for new java programmers to get right - how to handle exceptions - or more accurately the article talks to how *NOT* to handle exceptions.
Link
It was published in 2006 and I'm surprised I haven't seen it before now as it's really quite awesome (I came across it using Del.icio.us)
Anti-patterns they describe include
1) Log and rethrow
2) Throw the plain old generic java.lang.Exception
3) Throwing the Kitchen Sink
4) Catching java.lang.Exception
5) Destructive Wrapping
6) Log and Return Null
(Side note: I firmly believe you should NEVER return null from a method unless you really enjoy debugging NullPointerExceptions or giving them to other people's code - yah I know the Sun spec has several such cases in the core API but still . . . . .)
7) Catch and Ignore
8) Throw from Within Finally
9) Multi-Line Log Messages
10) Unsupported Operation Returning Null
11) Ignoring InterruptedException
12) Relying on getCause()
Two other great Exception handling articles (more from the POV of what to do than what *not* to do) are
a) Patterns for Generation, Handling and Management of Errors by Andy Longshaw and Eoin Woods
b) Best practices in EJB exception handling by Srikanth Shenoy
I particularly liked the Longshaw/Woods ideas of "Log at Distribution Boundaries" and "Split Domain and Technical Errors"
Labels: code quality, J2ee, java, programming, Software, standards








2 Comments:
Great article, Frank, thanks for the heads-up...
re: NEVER return null. Hmmm... there's a blog post right there, eh? I'll have to think on it but I'm not sure that we should say 'never'. Interesting...
6/13/2007 9:25 AM
There are many situations where returning null is the best option.
e.g.
Object o = map.get(key);
if (o!=null) {
return o;
}
// retry
is much simpler and faster than:
if (map.containsKey(key)) {
return map.get(key)'
}
//retry
Map lookups can be very expensive, especially for complex keys and long strings!
7/16/2007 9:38 PM
Post a Comment
Links to this post:
Create a Link
<< Home