Java finally and try-with-resources: Cleaning Up and Reading Stack Traces
Learn how Java's finally clause runs on every path, why return in finally is a trap, how try-with-resources closes AutoCloseable resources in reverse order with suppressed exceptions, and how to read and walk stack traces with StackWalker.
kvi5hnuCode Sprout team member12 min readOn this page
When an exception is thrown, the method stops running and exits. That's a problem if the method has acquired a resource that only it knows about, such as an open file, a network connection or a lock, and that must be released no matter what. This article covers the two tools Java offers for guaranteed cleanup: the finally clause and the far more common try-with-resources statement. It ends with stack traces: how to read them, and how to inspect the call stack from code.
The finally clause
One clumsy solution is to catch every exception, clean up, and rethrow. Then the cleanup code appears twice: once on the normal path and once in the handler. The finally clause solves this. Its code runs whether or not an exception occurred:
var in = new FileInputStream(. . .);
try {
// 1
code that might throw exceptions
// 2
} catch (IOException e) {
// 3
show error message
// 4
} finally {
// 5
in.close();
}
// 6
There are three possible scenarios:
- No exception. The whole
tryblock runs, then thefinallyclause, then the code after the statement: points 1, 2, 5, 6. - An exception that a catch clause handles, here an
IOException. The rest of thetryblock is skipped, the matchingcatchclause runs, then thefinallyclause. If thecatchclause completes normally, execution continues after the statement: 1, 3, 4, 5, 6. If thecatchclause throws an exception itself,finallystill runs, and the new exception goes to the caller: 1, 3, 5. - An exception that no catch clause handles. The rest of the
tryblock is skipped, thefinallyclause runs, and the exception goes to the caller: 1, 5.

You can use finally without any catch clause:
InputStream in = . . .;
try {
code that might throw exceptions
} finally {
in.close();
}
in.close() runs whatever happens in the try block. If an exception occurred, it continues to propagate after the finally clause, and some caller has to catch it.
Decoupling cleanup from error reporting
A clean way to combine cleanup and error handling is to nest two try statements, each with one job:
InputStream in = . . .;
try {
try {
code that might throw exceptions
} finally {
in.close();
}
} catch (IOException e) {
show error message
}
The inner statement makes sure the stream is closed. The outer one makes sure errors are reported. This is also more robust: an IOException thrown by close itself is reported by the outer handler too.
The try-with-resources statement
In practice you'll rarely write finally for cleanup, because Java 7 introduced a shortcut for this pattern:
open a resource
try {
work with the resource
} finally {
close the resource
}
It works with any class that implements AutoCloseable. That interface has a single method:
void close() throws Exception
In its simplest form:
try (Resource res = . . .) {
work with res
}
When the try block exits, normally or because of an exception, res.close() is called automatically. Here's how to print all words in a file:
try (var in = new Scanner(Path.of("in.txt"), StandardCharsets.UTF_8)) {
while (in.hasNext())
System.out.println(in.next());
}
You can declare several resources, separated by semicolons:
try (var in = new Scanner(Path.of("in.txt"), StandardCharsets.UTF_8);
var out = new PrintWriter("out.txt", StandardCharsets.UTF_8)) {
while (in.hasNext())
out.println(in.next().toUpperCase());
}
However the block exits, both in and out are closed. By hand, you'd need two nested try/finally statements to get this right. Resources are closed in the reverse order of their declaration. That matters when one resource depends on another, such as a statement created from a database connection: the statement is closed before the connection.
Since Java 9, you can also list an existing variable in the header, as long as it is effectively final:
public static void printAll(String[] lines, PrintWriter out) {
try (out) { // effectively final variable
for (String line : lines)
out.println(line);
} // out.close() called here
}
That's uncommon. It's usually clearer to close an object in the same scope that created it. A method that closes a resource it received as a parameter can surprise its caller.
If you don't need to refer to a resource in the block, for example a lock guard or a timer whose only job is to be closed, you can name it _ (Java 22): try (var _ = acquire()) { . . . }.
Suppressed exceptions
What if the try block throws an exception and close throws one too? Before try-with-resources, the exception from close in a finally block replaced the original one, so the real cause of the failure was lost.
try-with-resources gets this right:
- The original exception from the block is the one that propagates.
- Exceptions thrown by
closemethods are caught and attached to it withaddSuppressed. getSuppressed()returns them as an array, and stack traces print them underSuppressed:.

A try-with-resources statement can have its own catch and finally clauses. They run after the resources have been closed. So in a catch clause the resource is already closed, but any exception from closing it is available through getSuppressed().
You don't want to program all of this by hand. Whenever you need to close something, use try-with-resources.
Stack traces
A stack trace lists all method calls that are pending at a particular point in the execution of a program. You've seen them whenever a program ended with an uncaught exception. Here is one with a cause, as printed by the program at the end of this article:
java.io.UncheckedIOException: level2 gave up
at Solution.level2(Solution.java:101)
at Solution.level1(Solution.java:95)
at Solution.main(Solution.java:46)
Caused by: java.io.IOException: disk on fire
at Solution.level3(Solution.java:105)
at Solution.level2(Solution.java:99)
... 2 more
How to read it:
- The first line is the exception's
toString: class and message. - Each
atline is one stack frame, most recent call first: class, method, source file and line. Caused by:starts the cause's trace.... 2 moremeans the remaining frames are the same as in the trace above, so they're omitted.- When debugging, look for the first frame from your own code, and also for the deepest
Caused by:. That's usually where the real problem started.
Line numbers appear only if the class was compiled with debug information, which javac includes by default.
Getting a stack trace as text
printStackTrace() writes to System.err. To get the text, for logging or for a bug report, print into a StringWriter:
var t = new Throwable();
var out = new StringWriter();
t.printStackTrace(new PrintWriter(out));
String description = out.toString();
Throwable.getStackTrace() returns a StackTraceElement[] array, which you can examine frame by frame. In real applications you'll usually just pass the exception to a logger, which prints the trace for you (more on logging soon).
Walking the stack with StackWalker
You don't need an exception to inspect the stack. The StackWalker class (Java 9) gives you the current frames:
StackWalker walker = StackWalker.getInstance();
walker.forEach(frame -> analyze frame);
To process the frames lazily as a Stream<StackWalker.StackFrame>, for example to stop after the first few, use walk:
String caller = walker.walk(frames -> frames.skip(1).findFirst()
.map(StackWalker.StackFrame::getMethodName).orElse("?"));
Streams get their own treatment beyond this course; for now, forEach is enough.
StackWalker beats getStackTrace in two ways:
getStackTracecaptures the entire stack even if you need only one frame.StackWalkerwalks lazily.StackTraceElementonly has the class name. AStackFramecan also give you theClassobject, if the walker was created withStackWalker.Option.RETAIN_CLASS_REFERENCE.
Other options are SHOW_REFLECT_FRAMES (include reflection frames) and SHOW_HIDDEN_FRAMES (also include JVM-internal frames such as lambda implementation frames).
A StackFrame's toString returns class, method, file and line. The demo below prints the stack inside a recursive factorial method, so you can see a new frame added for each recursive call.
A complete example
The program below shows:
- the three paths through
finally; - the
return-in-finallytrap; - close order and suppressed exceptions with a custom
AutoCloseable; - an existing variable in the resource header;
StackWalker;- a printed stack trace with a cause.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// 1. the three paths through try/catch/finally
for (String mode : List.of("ok", "caught", "uncaught")) {
try {
trace(mode);
} catch (RuntimeException e) {
System.out.println(" caller got " + e.getClass().getSimpleName());
}
}
// 2. a return in finally hides the real result, and even swallows exceptions
System.out.println("badParse(\"42\") = " + badParse("42"));
System.out.println("badParse(\"zero\") = " + badParse("zero"));
// 3. try-with-resources: closed in reverse order, before catch and finally run
try (var a = new Resource("A", false); var b = new Resource("B", false)) {
System.out.println("using " + a + " and " + b);
} finally {
System.out.println("finally runs after both are closed");
}
// 4. body and close both fail: the body's exception wins, close's is suppressed
try (var _ = new Resource("C", true)) { // unnamed: we never use it
throw new IllegalStateException("body failed");
} catch (Exception e) {
System.out.println("caught " + e.getMessage());
for (Throwable s : e.getSuppressed())
System.out.println(" suppressed: " + s.getMessage());
}
// 5. an existing effectively final variable in the header
var buffer = new StringWriter();
var out = new PrintWriter(buffer);
printAll(new String[] { "line 1", "line 2" }, out);
System.out.print(buffer);
// 6. walking the stack
factorial(3);
// 7. a stack trace as text, with a cause
try {
level1();
} catch (RuntimeException e) {
var sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.print(sw);
StackTraceElement top = e.getStackTrace()[0];
System.out.println("top frame: " + top.getMethodName() + " line " + top.getLineNumber());
}
}
static void trace(String mode) {
try {
System.out.println(mode + ": 1 try starts");
if (!mode.equals("ok")) {
if (mode.equals("caught")) throw new IllegalArgumentException();
throw new UnsupportedOperationException();
}
System.out.println(mode + ": 2 try ends");
} catch (IllegalArgumentException e) {
System.out.println(mode + ": 3/4 catch runs");
} finally {
System.out.println(mode + ": 5 finally runs");
}
System.out.println(mode + ": 6 after the statement");
}
@SuppressWarnings("finally")
static int badParse(String s) {
try {
return Integer.parseInt(s);
} finally {
return 0; // DON'T: masks the return value and swallows exceptions
}
}
static void printAll(String[] lines, PrintWriter out) {
try (out) { // effectively final variable
for (String line : lines) out.println(line);
} // out.close() called here
}
static int factorial(int n) {
System.out.println("factorial(" + n + "):");
StackWalker.getInstance().forEach(frame -> System.out.println(" " + frame));
int r = n <= 1 ? 1 : n * factorial(n - 1);
System.out.println("return " + r);
return r;
}
static void level1() { level2(); }
static void level2() {
try {
level3();
} catch (IOException e) {
throw new UncheckedIOException("level2 gave up", e);
}
}
static void level3() throws IOException { throw new IOException("disk on fire"); }
}
class Resource implements AutoCloseable {
private final String name;
private final boolean failOnClose;
Resource(String name, boolean failOnClose) {
this.name = name;
this.failOnClose = failOnClose;
System.out.println("open " + name);
}
@Override
public void close() {
System.out.println("close " + name);
if (failOnClose) throw new IllegalStateException("close of " + name + " failed");
}
@Override
public String toString() { return name; }
}
ok: 1 try starts
ok: 2 try ends
ok: 5 finally runs
ok: 6 after the statement
caught: 1 try starts
caught: 3/4 catch runs
caught: 5 finally runs
caught: 6 after the statement
uncaught: 1 try starts
uncaught: 5 finally runs
caller got UnsupportedOperationException
badParse("42") = 0
badParse("zero") = 0
open A
open B
using A and B
close B
close A
finally runs after both are closed
open C
close C
caught body failed
suppressed: close of C failed
line 1
line 2
factorial(3):
Solution.factorial(Solution.java:89)
Solution.main(Solution.java:42)
factorial(2):
Solution.factorial(Solution.java:89)
Solution.factorial(Solution.java:90)
Solution.main(Solution.java:42)
factorial(1):
Solution.factorial(Solution.java:89)
Solution.factorial(Solution.java:90)
Solution.factorial(Solution.java:90)
Solution.main(Solution.java:42)
return 1
return 2
return 6
java.io.UncheckedIOException: level2 gave up
at Solution.level2(Solution.java:101)
at Solution.level1(Solution.java:95)
at Solution.main(Solution.java:46)
Caused by: java.io.IOException: disk on fire
at Solution.level3(Solution.java:105)
at Solution.level2(Solution.java:99)
... 2 more
top frame: level2 line 101
Common questions
Does finally run if I call System.exit in the try block?
No. System.exit shuts down the JVM without returning, so pending finally blocks don't run. Shutdown hooks do run. finally is also skipped if the JVM crashes or the process is killed.
Does finally run when the try block contains return?
Yes. The return value is computed first, then finally runs, then the method returns. That's why a return inside finally is so dangerous: it replaces the value, or swallows the exception, that was about to leave the method.
Do I still need finally now that try-with-resources exists?
Rarely. Use try-with-resources for anything AutoCloseable. finally remains useful for cleanup that isn't an object with close, such as lock.unlock() after lock.lock(), or restoring a field or a thread-local value.
What happens to the exception thrown by close()?
If the body threw an exception, the close exception is attached to it as a suppressed exception, and you can read it with getSuppressed(). If the body completed normally, the close exception propagates as the main exception.
Why does my stack trace say ... 5 more?
The cause's trace shares its outer frames with the enclosing exception's trace, so Java prints the shared frames only once. The omitted frames are exactly the last n frames of the trace above. Nothing has been lost.
API reference
java.lang.Throwable
| Method | Description |
|---|---|
Throwable(Throwable cause), Throwable(String message, Throwable cause) | Construct with a cause (Java 1.4) |
Throwable initCause(Throwable cause) | Sets the cause, or throws if one is already set. Returns this |
Throwable getCause() | The cause, or null |
StackTraceElement[] getStackTrace() | The call stack at the time this object was constructed |
void addSuppressed(Throwable t) | Adds a suppressed exception (Java 7). try-with-resources calls it for exceptions thrown by close |
Throwable[] getSuppressed() | All suppressed exceptions |
void printStackTrace(), printStackTrace(PrintWriter s) | Print the trace, including causes and suppressed exceptions |
Exception and RuntimeException have matching (Throwable cause) and (String message, Throwable cause) constructors.
java.lang.StackWalker (Java 9)
| Method | Description |
|---|---|
static StackWalker getInstance(), getInstance(StackWalker.Option option), getInstance(Set<StackWalker.Option> options) | Options: RETAIN_CLASS_REFERENCE, SHOW_HIDDEN_FRAMES, SHOW_REFLECT_FRAMES |
void forEach(Consumer<? super StackWalker.StackFrame> action) | Runs the action on each frame, most recent call first |
<T> T walk(Function<? super Stream<StackWalker.StackFrame>, ? extends T> function) | Applies the function to the stream of frames and returns its result |
StackWalker.StackFrame and StackTraceElement
| Method | Description |
|---|---|
String getFileName() | Source file name, or null if unavailable |
int getLineNumber() | Line number, or -1 if unavailable |
String getClassName() | Fully qualified class name |
Class<?> getDeclaringClass() | StackFrame only. Requires RETAIN_CLASS_REFERENCE, otherwise throws UnsupportedOperationException |
String getMethodName() | Method name. Constructors are <init>, static initializers <clinit>. Overloads can't be told apart |
boolean isNativeMethod() | true if the frame is in a native method |
String toString() | Class, method, file and line, when available |
Summary
finallyruns on every path out of atrystatement: normal completion, caught exception, uncaught exception.- Use nested
trystatements to separate cleanup (innertry/finally) from error reporting (outertry/catch). - Never
return,throw,breakorcontinuefromfinally. It masks results and swallows exceptions. - Prefer try-with-resources for anything
AutoCloseable. Resources close in reverse order, before the statement's owncatchandfinallyclauses run. - If both the body and
closethrow, the body's exception propagates and thecloseexception is suppressed (getSuppressed). - Stack traces list pending calls, most recent first, followed by
Caused by:andSuppressed:sections. - Use
printStackTrace(PrintWriter)to capture a trace as text andStackWalkerto inspect the current stack efficiently.
Practice Questions
A try block returns 1, and its finally clause prints "done" but has no return. What does the method return, and is "done" printed?
It returns 1. The value is computed, finally runs and prints done, and the method then returns the saved value. Only a return inside finally would change the result.
An exception is thrown in a try block, caught, and the catch clause throws a new exception. Does the finally clause run?
Yes. The finally clause runs on that path too (points 1, 3, 5), and then the new exception propagates to the caller.
In try (var a = new A(); var b = new B()) { … }, which resource is closed first?
b. Resources are closed in reverse order of declaration.
The body of a try-with-resources throws X and close throws Y. Which exception does the caller see, and where is the other one?
The caller sees X. Y is attached to X as a suppressed exception, available through X.getSuppressed() and printed under Suppressed: in the stack trace.
In a try-with-resources with a catch clause, is the resource still open when the catch clause runs?
No. Resources are closed before the statement's catch and finally clauses run.
What does "... 2 more" mean in a stack trace?
The cause's trace ends with 2 frames that are identical to frames already printed for the enclosing exception, so they are left out.
Why is StackWalker more efficient than new Throwable().getStackTrace() when you only need the caller's name?
getStackTrace captures every frame of the stack up front. StackWalker.walk produces frames lazily, so you can stop after the one or two you need.
Previous: Catching Exceptions in Java: try/catch, Multi-catch, Rethrowing and Chaining
Next: Java Exception Handling Best Practices: Tips Every Developer Should Know
Related reading
- Catching Exceptions in Java: try/catch, Multi-catch, Rethrowing and Chaining
- 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

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.