Java Tutorial · Advanced Java · Lesson 29 of 37

Java Exceptions

try, catch, finally, try-with-resources and custom exceptions.

try / catch / finally

Example 1
public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        try {
            System.out.println(numbers[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Oops: " + e.getMessage());
        } finally {
            System.out.println("finally always runs");
        }
        try {
            Object s = "text";
            Integer n = (Integer) s;
        } catch (ClassCastException | NullPointerException e) {
            System.out.println("Caught " + e.getClass().getSimpleName());
        }
    }
}

Output

Oops: Index 5 out of bounds for length 3
finally always runs
Caught ClassCastException

Run this on your computer — see “Get Started” for setup.

Checked vs unchecked

  • Checked exceptions (like IOException) must be caught or declared with throws — the compiler enforces it.
  • Unchecked exceptions (RuntimeException and subclasses: NullPointerException, IllegalArgumentException…) usually indicate bugs and don't need declaring.

try-with-resources

Resources that implement AutoCloseable (files, database connections) are closed automatically — even when an exception is thrown:

Example 2
public class Main {
    public static void main(String[] args) {
        try (Resource db = new Resource("database"); Resource file = new Resource("file")) {
            System.out.println("using both");
            throw new IllegalStateException("something failed");
        } catch (IllegalStateException e) {
            System.out.println("handled: " + e.getMessage());
        }
    }
}

class Resource implements AutoCloseable {
    private final String name;

    Resource(String name) {
        this.name = name;
        System.out.println("open " + name);
    }

    @Override
    public void close() {
        System.out.println("close " + name);
    }
}

Output

open database
open file
using both
close file
close database
handled: something failed

Run this on your computer — see “Get Started” for setup.

Custom exceptions

Example 3
public class Main {
    public static void main(String[] args) {
        try {
            withdraw(50, 80);
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage() + " (short by " + e.shortBy + ")");
        }
    }

    static double withdraw(double balance, double amount) throws InsufficientFundsException {
        if (amount > balance) throw new InsufficientFundsException(amount - balance);
        return balance - amount;
    }
}

class InsufficientFundsException extends Exception {
    final double shortBy;

    InsufficientFundsException(double shortBy) {
        super("Insufficient funds");
        this.shortBy = shortBy;
    }
}

Output

Insufficient funds (short by 30.0)

Run this on your computer — see “Get Started” for setup.

Test yourself

Which kind of exception must be caught or declared with throws?

  1. Checked exceptions
  2. Unchecked exceptions
  3. Errors
  4. RuntimeExceptions
Show answer

Answer: Checked exceptions