Exceptions in Java

Explains how to declare, throw, and catch exceptions in a Java program.

Prerequisites

Objectives

Errors and Exceptions

Partial List of Errors and Exceptions in java.lang and java.io

Object
   △
   └────
Throwable
     △
     ├─────
Error
     |    △
     |    ├──────
AssertionError
     |    ├──────
LinkageError
     |    ├──────
ThreadDeath
     |    ├──────
VirtualMachineError
     |    └──────
java.io.IOError
     |
     └─────
Exception
    △
    ├─────
ClassNotFoundException
    ├─────
NoSuchFieldException
    ├─────
NoSuchMethodException
    ├─────
RuntimeException1
    └─────
java.io.IOException2
RuntimeException
       △
       ├─────────
ArithmeticException
       ├─────────
ClassCastException
       ├─────────
IllegalArgumentException
       |           △
       |           ├───────────────
IllegalThreadStateException
       |           └───────────────
NumberFormatException
       |
       ├─────────
IndexOutOfBoundsException
       |             △
       |             ├─────────────
ArrayIndexOutOfBoundsException
       |             └─────────────
StringIndexOutOfBoundsException
       |
       ├─────────
NegativeArraySizeException
       └─────────
NullPointerException
 
java.io.IOException
       △
       ├─────────
java.io.EOFException
       ├─────────
java.io.FileNotFoundException
       └─────────
java.io.InterruptedIOException

Declaring that a Method Might Throw an Exception

Throwing an Exception

Handling an Exception

Complete Exception Handling Example

import java.io.*;

public class TestExceptions {
    public static void main(String[] args) {
        try {
            double s = addNumbers("numbers.dat");
            System.out.println(s);
        }
        catch (FileNotFoundException ex) {
            System.err.println(ex.getMessage());
        }
        catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
        catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
    }


    /* Reads and sums all the double numbers in a file. */
    public static double addNumbers(String filename)
        throws FileNotFoundException, IOException
    {
        File file = new File(filename);
        FileInputStream fin = new FileInputStream(file);
        DataInputStream din = new DataInputStream(fin);
        double sum = 0;
        try {
            /* This is an infinite loop because .readDouble()
             * throws an EOFException when it has reached the
             * end of a file which will terminate the loop. */
            while (true) {
                double d = din.readDouble();
                sum += d;
            }
        }
        catch (EOFException e) {
            /* We have reached the end of the file, which we
             * expected to happen, so we do nothing here.
             * When the EOFException is thrown the read loop
             * above will end. */
        }
        finally {
            din.close();
        }
        return sum;
    }
}

Common Mistake