What is an Exception

Errors at Runtime

An exception is an event that interrupts the normal flow of a program: dividing by zero, reading a missing file, calling a method on null. If nobody handles it, the program stops and prints a stack trace.

Example

The last line never runs because the exception is not handled.

public class Main {
    public static void main(String[] args) {
        int[] marks = { 80, 90, 70 };
        System.out.println("Starting");
        System.out.println(marks[3]);        // index 3 does not exist
        System.out.println("This line never runs");
    }
}

Output

Starting
Exception: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

The Exception Hierarchy

Throwable
                /         \
            Error          Exception
   (OutOfMemoryError,     /          \
    StackOverflowError)  IOException   RuntimeException
                         SQLException   (NullPointerException,
                         (checked)       IllegalArgumentException,
                                         ArithmeticException,
                                         IndexOutOfBoundsException)
                                         (unchecked)
  • Error: serious JVM problems. Do not catch them.
  • Exception: problems your program can handle.
  • RuntimeException and its children are unchecked; all other exceptions are checked.

Common Exceptions

ExceptionTypical cause
NullPointerExceptioncalling a method on a null reference
ArithmeticExceptioninteger division by zero
ArrayIndexOutOfBoundsExceptionbad array index
NumberFormatExceptionInteger.parseInt("abc")
ClassCastExceptionwrong downcast
IllegalArgumentExceptioninvalid method argument
IllegalStateExceptionmethod called at the wrong time
IOException (checked)file or network problem