java.net: Three Rules for Effective Exception Handling
One aspect of Java programming that I think is very difficult for new developers, myself included, is how to properly handled Exceptions. When do you throw them, when do you catch them and how do you handle them properly within a large system? I found this article, Three Rules for Effective Exception Handling, several months ago and it definitely helped to clear up some of the confusion.
Exceptions in Java provide a consistent mechanism for identifying and responding to error conditions. Effective exception handling will make your programs more robust and easier to debug. Exceptions are a tremendous debugging aid because they help answer these three questions:
- What went wrong?
- Where did it go wrong?
- Why did it go wrong?
When exceptions are used effectively, what is answered by the type of exception thrown, where is answered by the exception stack trace, and why is answered by the exception message. If you find your exceptions aren’t answering all three questions, chances are they aren’t being used effectively. Three rules will help you make the best use of exceptions when debugging your programs. These rules are: be specific, throw early, and catch late.
For me, the second point, throw early, was the most helpful. As soon as you detect a problem, throw an exception and be as specific about what went wrong as you can. In other words, don’t just throw a generic exception if the argument for a method was wrong, throw an IllegalArgumentException instead.
The article is well laid out and well written and definitely recommended for any java developer to read. I found it very usefull.