Exception Handling in Java

An exception is how a Java method reports that it cannot do its job: it stops normal execution and travels up the call stack until some code catches it. Java is unusual in having checked exceptions, which the compiler forces you to handle. This page explains the exception hierarchy and what happens when one is thrown, then shows try, catch and finally, how to read a stack trace, wrapping with causes, what exceptions cost, and how they behave in lambdas and threads.

Contents

What happens when an exception is thrown

When a throw statement runs, or the JVM detects an error such as dividing an integer by zero, the current method stops. The JVM then unwinds the call stack: it looks in the current method for a matching catch, and if there is none, leaves that method and looks in its caller, and so on. Every finally block on the way runs. If no method catches the exception, the thread ends and its stack trace is printed.

Every exception is an object of a class that extends Throwable. Where the class sits in the hierarchy decides how the compiler treats it:

The exception hierarchy
ClassKindMeaningExamples
ErrorUncheckedThe JVM itself is in trouble; usually not recoverableOutOfMemoryError, StackOverflowError
Exception (not runtime)CheckedA failure the caller should plan forIOException, SQLException
RuntimeExceptionUncheckedUsually a programming error, or a failure the caller cannot do much aboutNullPointerException, IllegalArgumentException

Checked exceptions must be either caught or declared with throws in the method signature, and the compiler enforces this. Unchecked exceptions can be thrown anywhere without being declared. Java is one of very few languages with checked exceptions, and they are debated: they document failures in the signature, but they are awkward with lambdas, as a later section shows. Most newer libraries throw unchecked exceptions.

try, catch and finally

The program parses network port numbers. The three inputs were chosen to take each path: a valid port, text that is not a number (caught and replaced by a default), and a number out of range (thrown to the caller). The last method shows what return inside finally does.

Java
public class TryCatchFinally {

    static int parsePort(String text) {
        try {
            int port = Integer.parseInt(text);
            if (port < 1 || port > 65535) {
                throw new IllegalArgumentException("port out of range: " + port);
            }
            return port;
        } catch (NumberFormatException e) {
            System.out.println("  not a number: " + text);
            return 8080;                                   // fall back to a default
        } finally {
            System.out.println("  finally runs for \"" + text + "\"");
        }
    }

    @SuppressWarnings("finally")
    static int finallyOverrides() {
        try {
            return 1;
        } finally {
            return 2;                                      // replaces the return value
        }
    }

    public static void main(String[] args) {
        System.out.println("result " + parsePort("443"));
        System.out.println("result " + parsePort("http"));
        try {
            parsePort("70000");
        } catch (IllegalArgumentException e) {
            System.out.println("caller caught: " + e.getMessage());
        }
        System.out.println("return in finally wins: " + finallyOverrides());
    }
}

Output:

Output
finally runs for "443"
result 443
  not a number: http
  finally runs for "http"
result 8080
  finally runs for "70000"
caller caught: port out of range: 70000
return in finally wins: 2
  • finally ran in all three cases: after a normal return, after a caught exception, and while an uncaught exception was leaving the method. That is its purpose: cleanup that must happen whatever the outcome. For closing resources, try-with-resources is better.
  • For "443", the finally line printed before "result 443": the return value was computed first, then finally ran, then the method returned.
  • The IllegalArgumentException for 70000 was not caught by catch (NumberFormatException e), so it passed through finally to main.
  • A return inside finally replaced the method's return value (2 instead of 1). It would also silently discard an exception in flight. javac warns about it with -Xlint:finally; never do it.

Catch order, multi-catch and the hierarchy

The program opens a file that does not exist, catching the specific exception before the general one, then handles two unrelated exceptions with one multi-catch, and finally classifies three exception classes.

Java
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Hierarchy {

    // Checked: the compiler forces callers to handle or declare it
    static void open(String path) throws IOException {
        try (FileReader reader = new FileReader(path)) {
            System.out.println("opened " + path + ", first char " + reader.read());
        }
    }

    public static void main(String[] args) {
        try {
            open("/no/such/file.txt");
        } catch (FileNotFoundException e) {               // more specific first
            System.out.println("FileNotFoundException: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("other I/O problem: " + e);
        }

        // Multi-catch for unrelated exceptions handled the same way
        for (String input : new String[] {"12", "x", null}) {
            try {
                int product = input.length() * Integer.parseInt(input);
                System.out.println("length * value = " + product);
            } catch (NumberFormatException | NullPointerException e) {
                System.out.println("bad input " + input + ": " + e.getClass().getSimpleName());
            }
        }

        // Where things sit in the hierarchy
        for (Class<?> c : new Class<?>[] {IOException.class, IllegalArgumentException.class,
                OutOfMemoryError.class}) {
            String kind = Error.class.isAssignableFrom(c) ? "Error (do not catch)"
                    : RuntimeException.class.isAssignableFrom(c) ? "unchecked" : "checked";
            System.out.println(c.getSimpleName() + ": " + kind);
        }
    }
}

Output:

Output
FileNotFoundException: /no/such/file.txt (No such file or directory)
length * value = 24
bad input x: NumberFormatException
bad input null: NullPointerException
IOException: checked
IllegalArgumentException: unchecked
OutOfMemoryError: Error (do not catch)
  • Catch clauses are tried in order, so the more specific FileNotFoundException must come before its superclass IOException. In the reverse order, javac refuses to compile, because the second clause could never run.
  • catch (NumberFormatException | NullPointerException e) (Java 7) handles unrelated exceptions with one block. The input "12" worked (2 × 12 = 24); "x" failed to parse and null failed on length().
  • Catching OutOfMemoryError or other Errors is almost never useful: the JVM may be in an inconsistent state, and the fix is configuration or code, not a retry.

Custom exceptions and chaining

A low-level exception such as NumberFormatException means little to a caller that asked to place an order. The usual fix is to catch it at the layer boundary and throw a domain exception that carries the original as its cause. The program does that for an order with the quantity "three".

Java
public class CustomAndChaining {

    // A domain exception that keeps the cause
    static class OrderException extends Exception {
        private final String orderId;

        OrderException(String orderId, String message, Throwable cause) {
            super(message, cause);
            this.orderId = orderId;
        }

        String orderId() {
            return orderId;
        }
    }

    static int loadQuantity(String raw) {
        return Integer.parseInt(raw);                      // may throw NumberFormatException
    }

    static void placeOrder(String id, String rawQty) throws OrderException {
        try {
            int qty = loadQuantity(rawQty);
            System.out.println("order " + id + " for " + qty + " items placed");
        } catch (NumberFormatException e) {
            // Wrap the low-level exception and keep it as the cause
            throw new OrderException(id, "invalid quantity in order " + id, e);
        }
    }

    public static void main(String[] args) {
        try {
            placeOrder("A-1", "3");
            placeOrder("A-2", "three");
        } catch (OrderException e) {
            System.out.println("failed: " + e.getMessage() + " (order " + e.orderId() + ")");
            System.out.println("caused by: " + e.getCause());
            StackTraceElement top = e.getCause().getStackTrace()[0];
            String where = top.getClassName() + "." + top.getMethodName();
            System.out.println("cause thrown in: " + where);
        }
    }
}

Output:

Output
order A-1 for 3 items placed
failed: invalid quantity in order A-2 (order A-2)
caused by: java.lang.NumberFormatException: For input string: "three"
cause thrown in: java.lang.NumberFormatException.forInputString
  • OrderException extends Exception, so it is checked and placeOrder declares it. It carries extra data, the order ID, which a generic exception could not.
  • Passing e to super(message, cause) keeps the original exception. getCause() returns it, and its stack trace still shows where it really happened.
  • Choose checked for failures the immediate caller is expected to handle, and unchecked (extend RuntimeException) for programming errors or failures that only a top-level handler can deal with.

Reading a stack trace

A stack trace is the most useful piece of information about a failure, and it is often read wrongly. The program prints one for the chained order exception exactly as a log would show it, and then shows what is lost when the cause is not passed on.

Java
import java.io.PrintStream;

public class StackTraces {

    static class OrderException extends Exception {
        OrderException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    static int parseQuantity(String raw) {
        return Integer.parseInt(raw);
    }

    static void placeOrder(String raw) throws OrderException {
        try {
            parseQuantity(raw);
        } catch (NumberFormatException e) {
            throw new OrderException("invalid quantity '" + raw + "'", e);
        }
    }

    public static void main(String[] args) {
        try {
            placeOrder("three");
        } catch (OrderException e) {
            PrintStream out = System.out;
            e.printStackTrace(out);                  // what a log normally shows
        }

        // A wrapper that drops the cause loses all of that information
        try {
            try {
                parseQuantity("x");
            } catch (NumberFormatException e) {
                throw new IllegalStateException("bad input");   // cause not passed on
            }
        } catch (IllegalStateException e) {
            System.out.println("without the cause: " + e + ", getCause() = " + e.getCause());
        }
    }
}

Output:

Output
StackTraces$OrderException: invalid quantity 'three'
	at StackTraces.placeOrder(StackTraces.java:19)
	at StackTraces.main(StackTraces.java:25)
Caused by: java.lang.NumberFormatException: For input string: "three"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at java.base/java.lang.Integer.parseInt(Integer.java:778)
	at StackTraces.parseQuantity(StackTraces.java:12)
	at StackTraces.placeOrder(StackTraces.java:17)
	... 1 more
without the cause: java.lang.IllegalStateException: bad input, getCause() = null
  • The first line is the exception class and message. Each at line is a method that was running, the most recent first, with the source file and line number.
  • Caused by: starts the cause's own trace. The root cause, the last Caused by, is usually where the problem started: here, Integer.parseInt called from parseQuantity at line 12.
  • ... 1 more means the remaining frame is the same as in the trace above (main), so it is not repeated.
  • The second exception was created without its cause, so getCause() is null and the information about which input failed and where is gone. Always pass the caught exception as the cause when wrapping; new X(e.getMessage()) is not enough.

Helpful NullPointerException messages

Since Java 14 (JEP 358, enabled by default since Java 15), a NullPointerException describes what exactly was null. The program triggers three typical ones: a chain of method calls, unboxing a missing map value, and a null array.

Java
import java.util.Map;

public class HelpfulNpe {

    record Address(String city) { }

    record Customer(String name, Address address) { }

    public static void main(String[] args) {
        Customer noAddress = new Customer("Ana", null);
        try {
            System.out.println(noAddress.address().city().length());
        } catch (NullPointerException e) {
            System.out.println("1: " + e.getMessage());
        }

        Map<String, Integer> stock = Map.of("apple", 3);
        try {
            int pears = stock.get("pear");
            System.out.println(pears);
        } catch (NullPointerException e) {
            System.out.println("2: " + e.getMessage());
        }

        int[] counts = null;
        try {
            counts[0]++;
        } catch (NullPointerException e) {
            System.out.println("3: " + e.getMessage());
        }
    }
}

Output:

Output
1: Cannot invoke "HelpfulNpe$Address.city()" because the return value of "HelpfulNpe$Customer.address()" is null
2: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
3: Cannot load from int array because "<local3>" is null
  • In a chain like customer.address().city().length(), the message names the call that returned null: address(). Before Java 14 the message was empty, and any of the three calls could have been the culprit.
  • The second message reveals the hidden unboxing call, Integer.intValue(), on the result of Map.get; see autoboxing.
  • Local variables appear as <local3> because the code was compiled without debug information. Compiling with javac -g, which build tools such as Maven and Gradle do by default, shows the real name, "counts".

What exceptions cost

Creating an exception records the stack trace, which means walking every frame of the call stack. The program throws exceptions from 50 calls deep with and without stack traces, then validates 200,000 malformed number strings by catching NumberFormatException and by checking the characters first. Each timing is the best of 3 runs, a rough comparison rather than a benchmark.

Java
public class ExceptionCost {

    static class Quick extends RuntimeException {
        Quick() {
            super("no stack trace", null, false, false);  // writableStackTrace = false
        }
    }

    static int depth(int n, RuntimeException toThrow) {
        if (n == 0) {
            throw toThrow == null ? new IllegalArgumentException("deep") : new Quick();
        }
        return depth(n - 1, toThrow) + 1;
    }

    static boolean isNumberByException(String s) {
        try {
            Integer.parseInt(s);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    static boolean isNumberByCheck(String s) {
        if (s.isEmpty()) {
            return false;
        }
        for (int i = 0; i < s.length(); i++) {
            if (!Character.isDigit(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    interface Job {
        int run();
    }

    static void time(String name, Job job) {
        long best = Long.MAX_VALUE;
        int result = 0;
        for (int run = 0; run < 3; run++) {
            long t = System.nanoTime();
            result = job.run();
            best = Math.min(best, System.nanoTime() - t);
        }
        System.out.printf("%-44s %,6d ms (%d)%n", name, best / 1000000, result);
    }

    public static void main(String[] args) {
        int n = 200000;
        String[] inputs = {"1234x", "98765y", "12-3", "4o4", "1e6", "77 ", "12.5", "9,999"};
        time("throw IllegalArgumentException, 50 frames deep", () -> {
            int caught = 0;
            for (int i = 0; i < n; i++) {
                try {
                    depth(50, null);
                } catch (IllegalArgumentException e) {
                    caught++;
                }
            }
            return caught;
        });
        time("throw without a stack trace, 50 frames deep", () -> {
            int caught = 0;
            for (int i = 0; i < n; i++) {
                try {
                    depth(50, new Quick());
                } catch (Quick e) {
                    caught++;
                }
            }
            return caught;
        });
        time("validate 200,000 bad inputs with parseInt+catch", () -> {
            int ok = 0;
            for (int i = 0; i < n; i++) {
                ok += isNumberByException(inputs[i & 7]) ? 1 : 0;
            }
            return ok;
        });
        time("validate 200,000 bad inputs with a check", () -> {
            int ok = 0;
            for (int i = 0; i < n; i++) {
                ok += isNumberByCheck(inputs[i & 7]) ? 1 : 0;
            }
            return ok;
        });
    }
}

Output (2-CPU Linux machine, JDK 21; times will differ on yours):

Output
throw IllegalArgumentException, 50 frames deep    537 ms (200000)
throw without a stack trace, 50 frames deep     215 ms (200000)
validate 200,000 bad inputs with parseInt+catch    107 ms (0)
validate 200,000 bad inputs with a check          1 ms (0)
  • Throwing and catching an exception 50 frames deep cost a few microseconds each. Turning off the stack trace (the four-argument constructor with writableStackTrace set to false) roughly halved that; the rest is unwinding the frames. Exceptions without stack traces are much harder to debug, so use them only for special cases such as very frequent, expected signals.
  • Validating with parseInt and catch was about a hundred times slower than checking the characters, because every bad input created an exception with a stack trace. Exceptions are fine for exceptional cases; for input that is often invalid, check first.

Exceptions in lambdas and threads

Two places behave differently from ordinary method calls. The program loads files inside a stream, where a checked exception is not allowed, and lets an exception escape from a background thread.

Java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;

public class LambdasAndThreads {

    static String load(String name) throws IOException {
        if (name.startsWith("missing")) {
            throw new IOException("cannot read " + name);
        }
        return name.toUpperCase();
    }

    public static void main(String[] args) throws InterruptedException {
        // A lambda for Function cannot throw a checked exception: wrap it
        List<String> names = List.of("a.txt", "missing.txt", "b.txt");
        try {
            List<String> loaded = names.stream().map(n -> {
                try {
                    return load(n);
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }).toList();
            System.out.println(loaded);
        } catch (UncheckedIOException e) {
            System.out.println("stream failed: " + e.getCause().getMessage());
        }

        // An exception that escapes a thread ends only that thread
        Thread worker = new Thread(() -> {
            throw new IllegalStateException("worker crashed");
        }, "worker-1");
        worker.setUncaughtExceptionHandler((t, e) ->
                System.out.println("handler: " + t.getName() + " died with " + e.getMessage()));
        worker.start();
        worker.join();
        System.out.println("main thread still running");
    }
}

Output:

Output
stream failed: cannot read missing.txt
handler: worker-1 died with worker crashed
main thread still running
  • The Function interface used by map declares no checked exceptions, so a lambda that calls load must catch IOException. The standard pattern is to wrap it in UncheckedIOException, and unwrap it with getCause() where the stream is used.
  • An exception that escapes a thread's run method ends only that thread. Its UncaughtExceptionHandler received it, and main continued. Without a handler, the JVM prints the stack trace to standard error.
  • With an ExecutorService, an exception inside a task is stored in its Future and rethrown, wrapped in ExecutionException, by get(). If nobody calls get(), it is silently lost; the ExecutorService page shows this.

Good and bad practice

Exception handling practices
DoAvoid
Catch the most specific exception you can handlecatch (Exception e) deep inside business code
Pass the original exception as the cause when wrappingthrow new X(e.getMessage())
Handle it, or let it propagateAn empty catch block that hides the failure
Log once, where it is finally handledLogging and rethrowing at every layer, which repeats the trace
Validate input before calling methods that throw for itExceptions as normal control flow
try-with-resources for anything closeableClosing resources by hand in finally
Restore the interrupt flag when catching InterruptedExceptionSwallowing InterruptedException
Include the bad value in the messageMessages like "invalid input"