It is not a matter of IF but WHEN things will go wrong in a computer program. Sometimes there are bugs, errors of one form or another. There are also unforeseen use cases. You can never assume a computer program is perfect. Exception-Handling helps us to catch erroneous events and devise means of correcting them. We discuss this topic here since exception-handling can take more code than should be put into the main line of execution. In such cases, a method in an exception-handling class should be called. Exception handling mechanisms allow a program to continue executing, instead of terminating it abruptly, even if an error occurs in the program.
10.3 Java’s Exception Hierarchy
The Java class library contains a number of predefined exceptions, some
of which are shown in Figure 10.4. The most general type of exception,
java.lang.Exception, is located in the java.lang package, but most
of its subclasses are contained in other packages. Some of the various IOException classes are contained in the java.io package, while others are contained in the java.net package. In general, exception classes are placed in the package that contains the methods that throw those
exceptions.
Each of the classes in Figure 10.4 identifies a particular type of
exception, and each is a subclass of the Exception class. Obviously a subclass defines a more specific exception than its superclass. Thus, both ArrayIndexOutOfBoundsException and
StringIndexOutOfBoundsException are more specific than IndexOutOfBoundsException.
Table 10.1 gives a brief summary of some of the most important exceptions. You’ve undoubtedly encountered some of these exceptions, because
they are thrown by methods we have used repeatedly in programming
examples. Table 10.2 summarizes the exceptions raised by some of the
methods we’ve used most frequently.
SELF-STUDY EXERCISE
EXERCISE 10.1 What type of exception would be thrown for the following statements?
a. Integer.parseInt("26.2");
b. String s; s.indexOf(’a’);
c. String s = "hello"; s.charAt(5);