← All lessons
Intermediate Java · Lesson 6 of 9

Exceptions

Things go wrong while programs run: a file is missing, a user types letters where a number belongs, a network is down. Java reports these as exceptions, objects that describe the problem. Left alone, an exception stops the program. With try and catch you can handle it and carry on.

Java
String[] inputs = {"42", "abc", "7"};
for (String s : inputs) {
    try {
        int n = Integer.parseInt(s);
        System.out.println("Got " + n);
    } catch (NumberFormatException e) {
        System.out.println("Not a number: " + s);
    }
}
System.out.println("Done");
Prints
Got 42
Not a number: abc
Got 7
Done

Java runs the try block. If a line in it throws, the rest of the try is skipped and Java jumps to the first catch whose type matches. If nothing throws, the catch is skipped. Either way, the program carries on after it. e is the exception object; e.getMessage() gives its message.

A try can have several catch blocks, checked in order, and finally runs at the end whatever happened, even after a return. It's for clean-up that must always happen.

Java
public class Main {
    static int divide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            System.out.println("Can't divide by zero");
            return 0;
        } finally {
            System.out.println("checked " + a + "/" + b);
        }
    }

    public static void main(String[] args) {
        System.out.println(divide(10, 2));
        System.out.println(divide(1, 0));
    }
}
Prints
checked 10/2
5
Can't divide by zero
checked 1/0
0

Throwing your own

Your own code can throw too, with throw, when it's given something it can't work with. IllegalArgumentException is the usual one for a bad parameter. Throwing early, with a clear message, beats carrying on with a bad value and failing somewhere confusing later.

Java
public class Main {
    static int ticketPrice(int age) {
        if (age < 0) throw new IllegalArgumentException("age can't be negative: " + age);
        return age < 12 ? 5 : 10;
    }

    public static void main(String[] args) {
        System.out.println(ticketPrice(30));
        try {
            ticketPrice(-3);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Prints
10
Error: age can't be negative: -3

Checked and unchecked

Java has two kinds. Unchecked exceptions (subclasses of RuntimeException, like NullPointerException, IllegalArgumentException and ArithmeticException) usually mean a bug, and you don't have to mention them. Checked exceptions (like IOException when reading a file) are problems a correct program can still meet, and the compiler makes you deal with them: catch them, or add throws IOException to the method to pass them on to the caller.

You can make your own exception class by extending one of these. A name that says what went wrong makes errors much easier to handle and to read in a log:

Java
public class Main {
    static class OutOfStockException extends Exception {
        OutOfStockException(String item) { super(item + " is out of stock"); }
    }

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

    public static void main(String[] args) {
        try {
            order("pens", 3);
            order("ink", 0);
            order("paper", 9);
        } catch (OutOfStockException e) {
            System.out.println(e.getMessage());
        }
    }
}
Prints
Ordered pens
ink is out of stock

Paper is never ordered: once order("ink", 0) throws, the rest of the try is skipped.

Reading a stack trace

An exception nobody catches prints its class, its message and a stack trace, the chain of method calls that led there, newest first. Find the top line in your own code: that's where it happened. A Caused by: section means one exception was wrapped in another; the real cause is usually the last one.

Log
Exception in thread "main" java.lang.IllegalStateException: could not load order 17
	at shop.OrderService.load(OrderService.java:42)
	at shop.Main.main(Main.java:9)
Caused by: java.lang.NumberFormatException: For input string: "12x"
	at java.base/java.lang.Integer.parseInt(Integer.java:661)
	at shop.OrderService.parseQuantity(OrderService.java:58)
	... 2 more

Catch an exception only where you can do something useful about it: retry, use a default, tell the user. An empty catch block that swallows errors hides bugs.

Practice

What does this print?

try {
    System.out.println("A");
    int x = 5 / 0;
    System.out.println("B");
} catch (ArithmeticException e) {
    System.out.println("C");
}
System.out.println("D");
More info

Quick reference

try { } catch (Type e) { }Run the try; on that exception, run the catch.
finally { }Always runs, for clean-up.
throw new X("why");Report a problem yourself.
IllegalArgumentExceptionThe usual exception for a bad parameter.
e.getMessage()The exception's message.
checked (IOException)Must be caught or declared with throws.
unchecked (RuntimeException)Usually a bug; no need to declare.
Caused by:In a stack trace, the exception underneath; often the real cause.

Related courses