Page 600 - Introduction to Programming with Java: A Problem Solving Approach
P. 600

                566 Chapter 14 Exception Handling
 Class Hierarchy for Exception Classes
 Throwable
    Error
unchecked exceptions for system error (e.g., VirtualMachineError)
RuntimeException
checked exceptions (e.g., IOException)
Exception
    unchecked exceptions
(e.g., InputMismatchException, NumberFormatException)
 Figure 14.7 Exception class hierarchy
Figure 14.7 shows the class hierarchy for all exceptions. It reiterates the point that unchecked exceptions are descendants of the RuntimeException class. It also shows that some unchecked exceptions are de- scendants of the Error class. In the interest of keeping things simple, we didn’t mention the Error class above. You probably won’t encounter its exceptions.
Programmer-Defined Exception Classes
Apago PDF Enhancer
It’s possible for programmers to define their own exception classes. Such programmer-defined exception classes must be derived from the Exception class or from a subclass of the Exception class. Generally speaking, you should limit yourself to predefined exception classes, because programmer-defined exception classes tend to fragment error-handling activities, and that makes programs harder to understand.
14.7 Unchecked Exceptions
As you learned in the previous section, unchecked exceptions need not be checked with a try-catch mechanism. However, at runtime, if the JVM throws an unchecked exception and there’s no catch block to catch it, the program will crash.
Strategies for Handling Unchecked Exceptions
If your program contains code that might throw an unchecked exception, there are two alternate strategies for dealing with it:
1. Use a try-catch structure.
or
2. Don’t attempt to catch the exception, but write the code carefully so as to avoid the possibility of the
exception being thrown.
In the getIntFromUser method in Figure 14.6, we employed the first strategy—we used a try- catch structure to handle the dangerous parseInt method call. Normally, you should use a try-catch structure for parse method calls (parseInt, parseLong, parseDouble, and so on) because that leads
 










































































   598   599   600   601   602