Sponsored Link •
This article gives design guidelines that pertain to exceptions. It shows how to decide when to use exceptions, using examples from the Java API that illustrate appropriate uses of exceptions. In addition, the article provides some general guidelines that can help you use exceptions in those situations where you've decided they are appropriate.
Five months ago, I began a mini-series of articles about designing objects. In this Design Techniques article, I'll continue that series by looking at design principles that concern error reporting and exceptions. I'll assume in this article that you know what exceptions are and how they work. If you would like a refresher on exceptions in general, see the companion article, "Exceptions in Java".
The benefits of exceptions
Exceptions have several benefits. First, they allow you to separate error handling code from normal code. You can surround the code that you expect to execute 99.9% of the time with a try block, and then place error handling code in catch clauses -- code that you don't expect to get executed often, if ever. This arrangement has the nice benefit of making your "normal" code less cluttered.
If you feel that a method doesn't know how to handle a particular
error, you can throw an exception from the method and let someone else
deal with it. If you throw a "checked" exception, you enlist the help
of the Java compiler to force client programmers to deal with the
potential exception, either by catching it or declaring it in the
throws clause of their methods. The fact that Java
compilers make sure checked exceptions are handled helps make Java
programs more robust.