Fundamentals 3 min read

Why Exceptions and Returns in a Java finally Block Can Lose the Original Exception

The article explains that when a Java finally block throws a new exception or contains a return statement, the original exception from the try block is discarded, demonstrates this with code examples, shows the resulting output, and advises best‑practice handling to avoid losing exception information.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Why Exceptions and Returns in a Java finally Block Can Lose the Original Exception

In Java, if a finally block contains a throw statement or a return , the exception or return value from the try block is discarded, causing the original exception to be lost.

Example – finally throws an exception

public class FinallyLostException {
    public static void main(String[] args) {
        test();
    }

    private static void test() {
        try {
            throw new RuntimeException("try exe");
        } finally {
            throw new RuntimeException("finally exe");
        }
    }
}

Running the program produces:

Exception in thread "main" java.lang.RuntimeException: finally exe
    at com.example.springcloudtest.spring.postprocessor.FinallyLostException.test(FinallyLostException.java:15)
    at com.example.springcloudtest.spring.postprocessor.FinallyLostException.main(FinallyLostException.java:8)

As shown, the exception from the finally block overrides the one thrown in try .

Example – finally contains a return statement

public class FinallyLostException {
    public static void main(String[] args) {
        test();
    }

    private static void test() {
        try {
            throw new RuntimeException("try exe");
        } finally {
            return;
        }
    }
}

This program finishes without any exception being propagated because the return in finally suppresses the exception.

These behaviors are considered design flaws in Java's exception handling compared to languages like C++. In real projects, an exception thrown in a finally block can cause the original stack trace to disappear from logs.

Summary

To avoid losing exceptions, do not place return statements in finally blocks, and ensure any code inside finally catches and logs exceptions (e.g., using Throwable.printStackTrace() ) instead of re‑throwing them.

exception handlingProgrammingbest practicesfinally
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.