Skip to main content
Engineering LibreTexts

10.2: Java’s Exception Hierarchy

  • Page ID
    15120
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    [pg-sec-excepthier]

    The Java class library contains a number of predefined exceptions, some of which are shown in Figure [fig-excepthier]. 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 [fig-excepthier] 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.

    ll
    Class&Description

    ArithmeticException&Division by zero or some other kind of arithmetic problem&An array index is less than zero or greater &than or equal to the array’s length&Reference to a file that cannot be found&Calling a method with an improper argument&An array or string index is out of bounds&Reference to an object that has not been instantiated&Use of an illegal number format, such as when calling a method&A String index is less than zero or greater than &or equal to the String’s length

    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.

    llll
    Class& Method & Exception Raised & Description

    Double&valueOf(String)&NumberFormatException&The String is not a double&parseInt(String)&NumberFormatException&The String is not a int&String(String)&NullPointerException&The String is null &indexOf(String)&NullPointerException&The String is null &lastIndexOf(String)&NullPointerException&The String is null &charAt(int)&StringIndexOutOfBoundsException&The int is not a valid index &substring(int)&StringIndexOutOfBoundsException&The int is not a valid index &substring(int,int)&StringIndexOutOfBoundsException&An int is not a valid index

    What type of exception would be thrown for the following statements?

    Integer.parseInt("26.2");

    String s; s.indexOf(’a’);

    String s = "hello"; s.charAt(5);

    Checked and Unchecked Exceptions

    Java’s exception hierarchy is divided into two types of exceptions. A checked exception is one that can be analyzed by the Java compiler. Checked exceptions are thrown by methods such as the BufferedReader.readLine() method, in which there is a substantial likelihood that something might go wrong. When the compiler encounters one of these method calls, it checks whether the program either handles or declares the exception. Compile-time checking for these exceptions is to reduce the number of exceptions that are not properly handled within a program. This improves the security of Java programs.

    The throws Clause

    The IOException, which we encountered in Chapter 4 , is a checked exception. The Java compiler knows that readLine() is a method that can throw an IOException. A method that contains an expression that might throw a checked exception must either handle the exception or declare it. Otherwise, the compiler would generate a syntax error. The simplest way to avoid such a syntax error is to declare the exception, in our case that means qualifying the method header with the expression throws IOException.

    In general, any method that contains an expression that might throw a checked expression must declare the exception. However, because one method can call another method, declaring exceptions can get a little tricky. If a method calls another method that contains an expression that might throw an unchecked exception, then both methods must have a throws clause. For example, consider the following program:

    import java.io.*;
    public class Example {
        BufferedReader input = new BufferedReader
                (new InputStreamReader(System.in));
        public void doRead() throws IOException {
            // May throw IOException
            String inputString = input.readLine();    
        }
        public static void main(String argv[]) 
                            throws IOException {
            Example ex = new Example();
            ex.doRead();
        }
    }

    In this case, the doRead() method contains a readLine() expression, which might throw an IOException. Therefore, the doRead() method must declare that it throws IOException. However, because doRead() is called by main(), the main() method must also declare the IOException.

    The alternative approach would be to catch the IOException within the body of the method. We will discuss this approach in the next section.

    Unchecked Exceptions

    An unchecked exception is any exception belonging to a subclass of RuntimeException (Fig. [fig-excepthier]). Unchecked exceptions are not checked by the compiler. The possibility that some statement or expression will lead to an ArithmeticException or NullPointerException is extremely difficult to detect at compile time. The designers of Java decided that forcing programmers to declare such exceptions would not significantly improve the correctness of Java programs.

    Therefore, unchecked exceptions do not have to be handled within a program. And they do not have to be declared in a throws clause. As shown in the chapter’s early divide-by-zero exception example, unchecked exceptions are handled by Java’s default exception handlers, unless your program takes specific steps to handle them directly. In many cases leaving the handling of such exceptions up to Java may be the best course of action, as we will see Section 5.

    The Exception Class

    The java.lang.Exception class itself is very simple, consisting of just two constructor methods (Fig. 10.5). The Throwable class, from which Exception is derived, is the root class of Java’s exception and error hierarchy. It contains definitions for the getMessage() and printStackTrace() methods, which are two methods that we will use frequently in our error-handling routines.

    Which of the following are examples of unchecked

    IOException

    IndexOutOfBoundsException

    NullPointerException

    ClassNotFoundException

    NumberFormatException


    This page titled 10.2: Java’s Exception Hierarchy is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.