TExcelTAD
Home › Java › Java Exceptions

Java Exceptions

Things go wrong at runtime: a file is missing, a user types letters where a number was expected, a network connection drops. When Java hits such a problem it throws an exception — an object describing what went wrong. If nothing catches it, the program stops with an error message and a stack trace. With try and catch you can handle the problem and keep going.

try and catch

Put the code that might fail in a try block. If an exception is thrown, Java jumps straight to a matching catch block; the rest of the try block is skipped:

java · try it yourself
class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};
        try {
            System.out.println("Before");
            System.out.println(numbers[5]);       // throws
            System.out.println("Never printed");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught: " + e.getMessage());
        }
        System.out.println("Program continues");
    }
}
Before
Caught: Index 5 out of bounds for length 3
Program continues

The variable e is the exception object. Useful methods are getMessage() (the description) and getClass().getSimpleName() (its type).

Multiple catch blocks and finally

A try can have several catch blocks — Java uses the first one that matches. You can also catch several types in one block with |. A finally block runs always, whether an exception happened or not — perfect for clean-up:

java · try it yourself
class Main {
    static void process(String input) {
        try {
            int value = Integer.parseInt(input);
            System.out.println("100 / " + value + " = " + (100 / value));
        } catch (NumberFormatException e) {
            System.out.println("'" + input + "' is not a number");
        } catch (ArithmeticException | NullPointerException e) {
            System.out.println("Math problem: " + e.getClass().getSimpleName());
        } finally {
            System.out.println("-- done with '" + input + "'");
        }
    }

    public static void main(String[] args) {
        process("4");
        process("abc");
        process("0");
    }
}
100 / 4 = 25
-- done with '4'
'abc' is not a number
-- done with 'abc'
Math problem: ArithmeticException
-- done with '0'

The exception hierarchy

All exceptions are objects whose classes extend Throwable:

Throwable
├── Error                      serious JVM problems (OutOfMemoryError) - don't catch
└── Exception
    ├── IOException, ...       checked exceptions
    └── RuntimeException       unchecked exceptions
        ├── NullPointerException
        ├── IllegalArgumentException
        │   └── NumberFormatException
        ├── ArithmeticException
        └── IndexOutOfBoundsException
Checked exceptions Unchecked exceptions
Extend Exception (not RuntimeException) RuntimeException
Typical cause outside problems: files, network programming bugs: null, bad index
Compiler rule must be caught or declared with throws no requirement
Examples IOException, SQLException NullPointerException, IllegalStateException

A catch block for a parent class also catches all its subclasses, so put specific catches before general ones.

Throwing exceptions yourself

Use throw to signal that something is wrong — for example invalid arguments. If you throw a checked exception, the method must declare it with throws:

java · try it yourself
class Main {
    static double withdraw(double balance, double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Amount must be positive: " + amount);
        }
        if (amount > balance) {
            throw new IllegalStateException("Insufficient funds");
        }
        return balance - amount;
    }

    static String readConfig(String name) throws java.io.IOException {
        if (!name.endsWith(".conf")) {
            throw new java.io.IOException("Unsupported file: " + name);
        }
        return "debug=true";
    }

    public static void main(String[] args) {
        double[] attempts = {30, -5, 500};
        for (double a : attempts) {
            try {
                System.out.println("New balance: " + withdraw(100, a));
            } catch (IllegalArgumentException | IllegalStateException e) {
                System.out.println("Rejected: " + e.getMessage());
            }
        }
        try {
            System.out.println(readConfig("app.conf"));
            System.out.println(readConfig("app.txt"));
        } catch (java.io.IOException e) {
            System.out.println("I/O error: " + e.getMessage());
        }
    }
}
New balance: 70.0
Rejected: Amount must be positive: -5.0
Rejected: Insufficient funds
debug=true
I/O error: Unsupported file: app.txt

Custom exceptions

Create your own exception type by extending Exception (checked) or RuntimeException (unchecked). A descriptive name makes errors self-explanatory:

java · try it yourself
class OutOfStockException extends Exception {
    private final String item;

    OutOfStockException(String item, int requested, int available) {
        super("Cannot order " + requested + " x " + item + ", only " + available + " left");
        this.item = item;
    }

    String getItem() { return item; }
}

class Main {
    static int stock = 3;

    static void order(String item, int qty) throws OutOfStockException {
        if (qty > stock) {
            throw new OutOfStockException(item, qty, stock);
        }
        stock -= qty;
        System.out.println("Ordered " + qty + " x " + item);
    }

    public static void main(String[] args) {
        try {
            order("lamp", 2);
            order("lamp", 2);
        } catch (OutOfStockException e) {
            System.out.println(e.getMessage());
            System.out.println("Notify supplier about: " + e.getItem());
        }
    }
}
Ordered 2 x lamp
Cannot order 2 x lamp, only 1 left
Notify supplier about: lamp

try-with-resources

Objects that hold resources — files, network connections — must be closed. A try-with-resources statement closes them automatically, even if an exception occurs. Any class implementing AutoCloseable works:

java · try it yourself
class Connection implements AutoCloseable {
    private final String name;

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

    void send(String msg) {
        if (msg.isEmpty()) throw new IllegalArgumentException("empty message");
        System.out.println(name + " <- " + msg);
    }

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

class Main {
    public static void main(String[] args) {
        try (Connection c = new Connection("db")) {
            c.send("SELECT 1");
            c.send("");
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
open db
db <- SELECT 1
close db
Error: empty message

The resource is closed before the catch block runs.

Tip: Catch exceptions only where you can do something useful — show a message, retry, use a default. An empty catch {} hides bugs and makes them very hard to find.

Test yourself

When does a finally block run?

  1. Only if an exception occurred
  2. Only if no exception occurred
  3. Always, after try (and catch if one ran)
  4. Never in practice

Which of these is a checked exception?

  1. NullPointerException
  2. IOException
  3. ArithmeticException
  4. IllegalArgumentException

Which keyword is used to raise an exception?

  1. throws
  2. throw
  3. raise
  4. catch