Exceptions and Debugging
- DEALING WITH ERRORS
- CATCHING EXCEPTIONS
- SOME TIPS ON USING EXCEPTIONS
- DEBUGGING TECHNIQUES
- USING A DEBUGGER
In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code would never have bugs. So far, we have mostly presented code as though we lived in this kind of perfect world. It is now time to turn to the mechanisms Java has for dealing with the real world of bad data and buggy code. Encountering errors is unpleasant. If a user loses all the work he or she did during a program session because of a coding mistake or some external circumstance, that user may forever turn away from your program. At the very least, you must:
- Notify the user of an error;
- Save all work;
- Allow users to gracefully exit the program.
For exceptional situations, such as bad input data with the potential to bomb the program, Java uses a form of error-trapping called, naturally enough, exception handling. Exception handling in Java is similar to that in C++ or Delphi. The first part of this chapter covers Java's exceptions. The second part of this chapter concerns finding bugs in your code before they cause exceptions at run time. Unfortunately, if you use just the SDK, then bug detection is the same as it was back in the Dark Ages. We give you some tips and a few tools to ease the pain. Then, we explain how to use the command-line debugger as a tool of last resort. For the serious Java developer, products such as Sun ONE Studio, Symantec's Café, and Inprise's JBuilder have quite useful debuggers. We give you an introduction to the Sun ONE Studio debugger.