|
|
|
|
Exception guidelines
Use exceptions to:
- Handle problems at the appropriate level. (Avoid catching exceptions unless
you know what to do with them).
- Fix the problem and call the method that caused the exception again.
- Patch things up and continue without retrying the method.
- Calculate some alternative result instead of what the method was supposed to
produce.
- Do whatever you can in the current context and rethrow the same
exception to a higher context.
- Do whatever you can in the current context and throw a different
exception to a higher context.
- Terminate the program.
- Simplify. (If your exception scheme makes things more complicated, then it
is painful and annoying to use.)
- Make your library and program safer. (This is a short-term investment for
debugging, and a long-term investment for application robustness.)
Summary
Improved error recovery is one of the most powerful ways that you can increase the robustness of your code. Error recovery is a fundamental concern for every program you write, but it’s especially important in Java, where one of the primary goals is to create program components for others to use. To create a robust system, each component must be robust. By providing a consistent error-reporting model with exceptions, Java allows components to reliably communicate problems to client code.
The goals for exception handling in Java are to simplify the creation of large, reliable programs using less code than currently possible, and to do so with more confidence that your application doesn’t have an unhandled error. Exceptions are not terribly difficult to learn, and are one of those features that provide immediate and significant benefits to your project.
|
|
|