Skip to main content

Section 11.2 Common Exception Classes

The Java Core Library provides many prewritten exception classes that it uses to indicate when runtime errors occur. Figure 11.2.1 illustrates many common exception classes making up part of this hierarchy.
Figure 11.2.1. Part of the Java Exception Class Hierarchy
In Figure 11.2.1 under the Throwable class, things that can go wrong in Java at runtime are grouped under two broad base classes, Error and Exception. Classes that derive from Error are very serious problems from which there is no recovery possible. These tend to occur when system resources are exhausted, such as when an instance of the OutOfMemoryError class, the StackOverflowError class, or the ominous ThreadDeath class, is thrown. Because we cannot catch and handle these exceptions, the best we can do is note that they exist and hope we never encounter them. The Exception class and its derived classes are of more interest because we can catch these exceptions and hopefully handle them in a productive way.
The Java Core Library includes a long list of classes that derive from the Exception base class. You are able to identify classes that derive from Exception by their name; all end with "Exception." The following lists several examples.
  • ArithmeticException - Occurs when dividing by 0
  • NullPointerException - A reference variable with a value of null was accessed
  • IndexOutOfBoundsException - an out-of-bounds index was passed to an ArrayList
  • ArrayIndexOutOfBoundsException - an out-of-bounds index was passed to an array
  • IllegalArgumentException - An illegal or inappropriate argument was passed to a method
Fortunately, when thrown, each of these and many additional exception objects may be caught and handled.
Furthermore, should you really need it, all Exception objects inherit the printStackTrace() method, which prints a stack trace for you.