Catching Exceptions in Java: try/catch, Multi-catch, Rethrowing and Chaining
Master catching exceptions in Java: how try/catch changes control flow, when to catch versus propagate, ordering multiple catch clauses, multi-catch with |, unnamed catch variables, and rethrowing, wrapping and chaining exceptions without losing the cause.
kvi5hnuCode Sprout team member11 min readOn this page
Throwing an exception is easy: you throw it and forget about it. Somebody, though, has to catch it, and catching takes more planning. Where should the handler go? What should it do? What if several things can go wrong? This article answers those questions and shows how to translate exceptions between layers of a program without losing information.
What happens if nobody catches an exception?
If an exception isn't caught anywhere, the thread it was thrown in ends. For a simple console program that means the program stops, and the console shows the exception type, its message and a stack trace, the list of method calls that were pending when it was thrown:
Exception in thread "main" java.lang.NumberFormatException: For input string: "forty-two"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at Solution.main(Solution.java:10)
Long-running programs behave differently. GUI frameworks and web servers catch exceptions from each event or request, log the stack trace, and carry on serving the next one. That's why you should keep an eye on the console or log while debugging such programs: a failure may be reported there without anything visibly crashing.
The try/catch statement
To catch an exception, wrap the code that may throw it in a try block and add a catch clause:
try {
code
more code
more code
} catch (ExceptionType e) {
handler for this type
}
The rules:
- If no code in the
tryblock throws, thecatchclause is skipped entirely. - If code in the
tryblock throws an exception of the type named in thecatchclause, or a subclass of it, the rest of thetryblock is skipped and the handler runs. Execution then continues after the wholetrystatement. - If the exception is of some other type, the method exits immediately, as if there were no
trystatement, and the search continues in the caller.
Here is typical code that reads a file:
public void read(String filename) {
try {
var in = new FileInputStream(filename);
int b;
while ((b = in.read()) != -1) {
process input
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
Most of the try block is straightforward: read and process bytes until the end of the file. The read method may throw an IOException. If it does, the program jumps out of the loop into the catch clause and prints a stack trace. For a toy program, that's acceptable.
Catch it, or pass it on?
There's another option that is often better: don't catch the exception at all, and let the caller deal with it. Then you must declare it:
public void read(String filename) throws IOException {
var in = new FileInputStream(filename);
int b;
while ((b = in.read()) != -1) {
process input
}
}
The compiler enforces throws declarations strictly. When you call a method that throws a checked exception, you must either handle it or declare it.
Which is better? The general rule:
Catch the exceptions you know how to handle. Propagate the ones you don't.
A low-level method like read has no idea what the right reaction is. Should the program ask the user for another file name? Try a backup location? Abort the whole import? Only code higher up knows. Adding throws IOException is nothing to be embarrassed about. Sending an exception to a capable handler is much better than swallowing it.
There's one situation where you have no choice. An overriding method may not declare more checked exceptions than the method it overrides. If you override a method that declares none, such as compareTo in Comparable, run in Runnable or apply in Function, you must catch every checked exception inside it, or wrap it in an unchecked one (shown below).
Unnamed catch variables
Sometimes the handler doesn't need the exception object at all. You only care that parsing failed, not why. Since Java 22, you can write an underscore instead of a name (it was a preview feature in Java 21):
static int parsePort(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException _) {
return 80; // fall back to a default
}
}
The _ tells readers, and linters, that ignoring the exception object is deliberate.
Catching several exception types
A try block can have several catch clauses, one per type you want to handle differently:
try {
code that might throw exceptions
} catch (FileNotFoundException e) {
emergency action for missing files
} catch (UnknownHostException e) {
emergency action for unknown hosts
} catch (IOException e) {
emergency action for all other I/O problems
}
The clauses are tested from top to bottom, and the first one that matches wins. So put the more specific types first:

If you put catch (IOException e) first, the clauses after it could never run. The compiler reports this as an error ("exception has already been caught").
Inside a handler, the exception object can tell you more:
e.getMessage()returns the detail message, if there is one.e.getClass().getName()returns the actual type of the exception object, which may be a subclass of the type you caught.
Multi-catch
If the handling for two exception types is the same, you can combine them in one clause with |:
try {
code that might throw exceptions
} catch (FileNotFoundException | UnknownHostException e) {
emergency action for missing files and unknown hosts
} catch (IOException e) {
emergency action for all other I/O problems
}
Facts about multi-catch:
- It is only needed for types that are not subclasses of one another. Writing
catch (FileNotFoundException | IOException e)is a compile error, becauseIOExceptionalready coversFileNotFoundException. - The exception variable is implicitly final. You can't assign a different value to
ein the handler. - Besides reading better, it avoids duplicated code. The compiler generates a single handler block for the shared clause.
Rethrowing and wrapping exceptions
You can throw an exception from inside a catch clause. The usual reason is to change the exception's type. If you build a subsystem that other programmers use, its callers care that your subsystem failed, not about every low-level detail. A servlet container wants to know that a servlet failed (ServletException), and a repository's callers want a repository exception rather than a raw SQLException or IOException.
You could copy only the message:
try {
access the database
} catch (SQLException e) {
throw new ServletException("database error: " + e.getMessage());
}
That loses the original stack trace and type. It's much better to make the original exception the cause of the new one:
try {
access the database
} catch (SQLException original) {
var e = new ServletException("database error", original);
throw e;
}
The caller who catches the high-level exception can still get at the original:
Throwable original = caughtException.getCause();

This chaining technique is highly recommended. You throw meaningful high-level exceptions without losing any detail of the original failure. Stack traces print the whole chain, each link introduced by Caused by:.
If the exception class you want to throw has no constructor that accepts a cause, call initCause once, before throwing:
var e = new NoSuchElementException("no such user");
e.initCause(original);
throw e;
initCause can be called only once, and not at all if a cause was already set through a constructor. Otherwise it throws IllegalStateException.
Wrapping checked exceptions in unchecked ones
Wrapping also solves a common annoyance: a checked exception occurs in a method that isn't allowed to throw one, such as a lambda body passed to forEach or map, or an override of run. Catch it and wrap it in a runtime exception. For I/O, the JDK provides java.io.UncheckedIOException exactly for this purpose:
paths.forEach(p -> {
try {
process(p);
} catch (IOException e) {
throw new UncheckedIOException("could not process " + p, e);
}
});
Code further up can catch UncheckedIOException and call getCause() to get the original IOException.
Logging and rethrowing unchanged
Sometimes you only want to record an exception and let it continue on its way:
try {
access the database
} catch (Exception e) {
logger.log(level, message, e);
throw e;
}
There is a subtlety. Suppose this code is in a method declared public void updateRecord() throws SQLException. You catch Exception and rethrow it, so it looks like the method should have to declare throws Exception. It doesn't. The compiler tracks that e originates from the try block. As long as the only checked exceptions that block can throw are SQLExceptions, and e isn't reassigned in the handler, declaring throws SQLException is enough. This is called precise rethrow.
A complete example
The program below demonstrates:
- the skipped remainder of a
tryblock; - ordered
catchclauses and multi-catch, including thedefaultneeded when switching on a multi-catch variable; - an unnamed catch variable;
- wrapping with a cause and with
initCause; UncheckedIOExceptioninside a lambda;- precise rethrow.
The fetch method simulates different failures so the output is predictable.
import java.io.*;
import java.net.UnknownHostException;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// 1. the rest of the try block is skipped once something throws
try {
System.out.println("before");
Integer.parseInt("forty-two");
System.out.println("never printed");
} catch (NumberFormatException e) {
System.out.println("caught: " + e.getMessage());
}
System.out.println("after the try statement");
// 2. several catch clauses: most specific first
for (int problem = 0; problem < 4; problem++) {
try {
fetch(problem);
System.out.println("fetch " + problem + ": ok");
} catch (FileNotFoundException e) {
System.out.println("fetch " + problem + ": missing file " + e.getMessage());
} catch (UnknownHostException e) {
System.out.println("fetch " + problem + ": unknown host " + e.getMessage());
} catch (IOException e) {
System.out.println("fetch " + problem + ": other I/O problem, " + e.getClass().getName());
}
}
// 3. multi-catch: one handler for unrelated types; e is implicitly final
for (int problem = 1; problem <= 2; problem++) {
try {
fetch(problem);
} catch (FileNotFoundException | UnknownHostException e) {
// the static type of e is IOException, so the switch needs a default
String what = switch (e) {
case FileNotFoundException fe -> "file";
case UnknownHostException ue -> "host";
default -> "?";
};
System.out.println("multi-catch: " + what);
} catch (IOException e) {
System.out.println("other");
}
}
// 4. an unnamed catch variable when you don't need the object (Java 22)
System.out.println("port = " + parsePort("http"));
// 5. wrapping a low-level exception in a higher-level one
try {
new UserRepository().load("u-17");
} catch (RepositoryException e) {
System.out.println(e.getMessage());
System.out.println(" caused by " + e.getCause());
}
// 6. initCause for exception classes without a cause constructor
try {
legacyLookup();
} catch (NoSuchElementException e) {
System.out.println(e.getMessage() + " <- " + e.getCause().getMessage());
}
// 7. a lambda can't throw a checked exception: wrap it in UncheckedIOException
try {
List.of(0, 3).forEach(p -> {
try {
fetch(p);
} catch (IOException e) {
throw new UncheckedIOException("fetch " + p + " failed", e);
}
});
} catch (UncheckedIOException e) {
System.out.println(e.getMessage() + ", original: " + e.getCause().getClass().getSimpleName());
}
// 8. precise rethrow: catch (Exception e) but declare only IOException
try {
logAndRethrow(1);
} catch (IOException e) {
System.out.println("rethrown unchanged: " + e.getClass().getSimpleName());
}
}
static void fetch(int problem) throws IOException {
switch (problem) {
case 1 -> throw new FileNotFoundException("data.csv");
case 2 -> throw new UnknownHostException("no.such.host");
case 3 -> throw new EOFException("truncated");
default -> { } // success
}
}
static int parsePort(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException _) {
return 80; // fall back to a default
}
}
static void legacyLookup() {
var e = new NoSuchElementException("no such user");
e.initCause(new IllegalStateException("cache was empty"));
throw e;
}
static void logAndRethrow(int problem) throws IOException {
try {
fetch(problem);
} catch (Exception e) {
System.out.println("log: " + e);
throw e; // the compiler knows only IOException can come out of the try block
}
}
}
class RepositoryException extends Exception {
private static final long serialVersionUID = 1L;
RepositoryException(String message, Throwable cause) { super(message, cause); }
}
class UserRepository {
String load(String id) throws RepositoryException {
try {
throw new IOException("connection reset"); // stand-in for real database access
} catch (IOException original) {
throw new RepositoryException("could not load user " + id, original);
}
}
}
before
caught: For input string: "forty-two"
after the try statement
fetch 0: ok
fetch 1: missing file data.csv
fetch 2: unknown host no.such.host
fetch 3: other I/O problem, java.io.EOFException
multi-catch: file
multi-catch: host
port = 80
could not load user u-17
caused by java.io.IOException: connection reset
no such user <- cache was empty
fetch 3 failed, original: EOFException
log: java.io.FileNotFoundException: data.csv
rethrown unchanged: FileNotFoundException
Common questions
Is catch (Exception e) a bad idea?
At the top level of a request handler, a thread, or main, catching Exception to log and recover is reasonable. Deep inside business logic it hides bugs and catches things you didn't plan for. Catch the specific types you can handle, and let the rest propagate.
What's wrong with an empty catch block?
It silently discards the failure, so the program continues in a possibly broken state with no trace of what happened. If ignoring an exception is genuinely correct, say so: name the variable _ (Java 22) or ignored, and add a comment explaining why.
Should I call e.printStackTrace()?
Only in quick experiments. It writes to System.err without timestamps or context, and production logs often miss it. Use a logger: logger.log(Level.WARNING, "Import failed", e), or log.warn("Import failed", e) with SLF4J.
How do I get the root cause of a chained exception?
Follow getCause() until it returns null, and guard against cycles in pathological cases. Stack traces already show the whole chain with "Caused by:", so you rarely need to do this by hand.
Does InterruptedException need special handling?
Yes. Catching it clears the thread's interrupt flag. If you can't propagate it, restore the flag with Thread.currentThread().interrupt() before continuing or wrapping it. Otherwise code higher up never learns that the thread was asked to stop. The concurrency material covers this in depth.
Summary
- An uncaught exception terminates its thread with a stack trace. Servers and GUIs usually catch, log and continue.
- In
try/catch, the first throw skips the rest of thetryblock. A matchingcatch(same type or a supertype) runs, and execution continues after the statement. Non-matching exceptions leave the method. - Catch what you can handle meaningfully. Declare (propagate) the rest. Overrides of methods without
throwsmust catch or wrap checked exceptions. - Order
catchclauses from specific to general. Usecatch (A | B e)for unrelated types that share a handler. The variable is final, and its type is the least upper bound of A and B. - Use
catch (SomeException _)when you don't need the object. - When translating exceptions between layers, pass the original as the cause (constructor or
initCause). Read it back withgetCause(). - Wrap checked exceptions in unchecked ones, such as
UncheckedIOException, where checked exceptions aren't allowed. - Precise rethrow lets
catch (Exception e) { ...; throw e; }keep a narrowthrowsclause.
Practice Questions
A try block calls a(), b() and c() in order. b() throws an exception caught by the catch clause. Does c() run?
No. The rest of the try block is skipped once an exception is thrown. The handler runs, then execution continues after the whole try statement.
Why doesn't this compile? catch (IOException e) { … } catch (FileNotFoundException e) { … }
FileNotFoundException is a subclass of IOException, so the first clause catches all of them and the second can never be reached. The compiler rejects unreachable catch clauses. Swap the order.
Is catch (FileNotFoundException | IOException e) legal?
No. The alternatives in a multi-catch can't be subclasses of each other. Just catch IOException.
In catch (FileNotFoundException | UnknownHostException e), what is the static type of e, and can you assign to it?
Its type is IOException, the least upper bound of the alternatives. It is implicitly final, so you can't assign to it.
You implement Comparator.compare and need to call a method that throws IOException. What are your options?
compare declares no checked exceptions, so you can't add throws IOException. Catch the exception and either handle it, or wrap it in an unchecked exception, such as new UncheckedIOException(e), and throw that.
What is lost if you rethrow with new ServletException("database error: " + e.getMessage())?
The original exception object: its type, its stack trace and its own cause chain. Pass it as the cause instead: new ServletException("database error", e).
A method declared throws SQLException contains try { … } catch (Exception e) { log(e); throw e; }. Why does it compile?
Precise rethrow. The compiler knows that the only checked exceptions the try block can throw are SQLExceptions, and e isn't reassigned, so rethrowing e can only throw what the try block could.
Previous: Throwing Exceptions and Creating Custom Exception Classes in Java
Next: Java finally and try-with-resources: Cleaning Up and Reading Stack Traces
Related reading
- Throwing Exceptions and Creating Custom Exception Classes in Java
- Java Exceptions: The Exception Hierarchy, Checked and Unchecked
- Java Reflection: The Class Class, Exceptions Primer and Loading Resources
- Java Dynamic Proxies: Implementing Interfaces at Runtime
- Java ServiceLoader: Loading Pluggable Service Implementations

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.