Exceptions: When Things Go Wrong

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.

Annotation 2020-03-29 161803

Annotation 2020-03-29 161904

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.

Annotation 2020-03-29 162650


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);