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 throwcatchfinally
Every exception is an object of a class that extends Throwable
| Class | Kind | Meaning | Examples |
|---|---|---|---|
Error | Unchecked | The JVM itself is in trouble; usually not recoverable | OutOfMemoryErrorStackOverflowError |
Exception | Checked | A failure the caller should plan for | IOExceptionSQLException |
RuntimeException | Unchecked | Usually a programming error, or a failure the caller cannot do much about | NullPointerExceptionIllegalArgumentException |
Checked exceptions must be either caught or declared with throws
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 returnfinally
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:
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
ran in all three cases: after a normalfinally , 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,returntry-with-resources is better.- For "443", the
line printed before "result 443": the return value was computed first, thenfinally ran, then the method returned.finally - The
for 70000 was not caught byIllegalArgumentException , so it passed throughcatch (NumberFormatException e) tofinally .main - A
insidereturn replaced the method's return value (2 instead of 1). It would also silently discard an exception in flight. javac warns about it withfinally ; never do it.-Xlint:finally
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.
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:
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
must come before its superclassFileNotFoundException . In the reverse order, javac refuses to compile, because the second clause could never run.IOException (Java 7) handles unrelated exceptions with one block. The input "12" worked (2 × 12 = 24); "x" failed to parse andcatch (NumberFormatException | NullPointerException e) failed onnull .length()- Catching
or otherOutOfMemoryError s is almost never useful: the JVM may be in an inconsistent state, and the fix is configuration or code, not a retry.Error
Custom exceptions and chaining
A low-level exception such as NumberFormatException
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:
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
extendsOrderException , so it is checked andException declares it. It carries extra data, the order ID, which a generic exception could not.placeOrder- Passing
toe keeps the original exception.super(message, cause) returns it, and its stack trace still shows where it really happened.getCause() - Choose checked for failures the immediate caller is expected to handle, and unchecked (extend
) for programming errors or failures that only a top-level handler can deal with.RuntimeException
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.
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:
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
line is a method that was running, the most recent first, with the source file and line number.at starts the cause's own trace. The root cause, the lastCaused by: , is usually where the problem started: here,Caused by called fromInteger.parseInt at line 12.parseQuantity means the remaining frame is the same as in the trace above (... 1 more ), so it is not repeated.main- The second exception was created without its cause, so
isgetCause() and the information about which input failed and where is gone. Always pass the caught exception as the cause when wrapping;null is not enough.new X(e.getMessage())
Helpful NullPointerException messages
Since Java 14 (JEP 358, enabled by default since Java 15), a NullPointerExceptionnullnull
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:
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
, the message names the call that returnedcustomer.address().city().length() :null . Before Java 14 the message was empty, and any of the three calls could have been the culprit.address() - The second message reveals the hidden unboxing call,
, on the result ofInteger.intValue() ; seeMap.getautoboxing . - Local variables appear as
because the code was compiled without debug information. Compiling with<local3> , which build tools such as Maven and Gradle do by default, shows the real name,javac -g ."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
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):
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
set towritableStackTrace ) 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.false - Validating with
andparseInt 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.catch
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.
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:
stream failed: cannot read missing.txt
handler: worker-1 died with worker crashed
main thread still running
- The
interface used byFunction declares no checked exceptions, so a lambda that callsmap must catchload . The standard pattern is to wrap it inIOException , and unwrap it withUncheckedIOException where the stream is used.getCause() - An exception that escapes a thread's
method ends only that thread. Itsrun received it, andUncaughtExceptionHandler continued. Without a handler, the JVM prints the stack trace to standard error.main - With an
, an exception inside a task is stored in itsExecutorService and rethrown, wrapped inFuture , byExecutionException . If nobody callsget() , it is silently lost; theget()ExecutorService page shows this.
Good and bad practice
| Do | Avoid |
|---|---|
| Catch the most specific exception you can handle | catch (Exception e) |
| Pass the original exception as the cause when wrapping | throw new X(e.getMessage()) |
| Handle it, or let it propagate | An empty catch |
| Log once, where it is finally handled | Logging and rethrowing at every layer, which repeats the trace |
| Validate input before calling methods that throw for it | Exceptions as normal control flow |
| try-with-resources for anything closeable | Closing resources by hand in finally |
Restore the interrupt flag when catching InterruptedException | Swallowing InterruptedException |
| Include the bad value in the message | Messages like "invalid input" |