Avoid Using return in a finally Block (Java)
This article explains why using a return statement inside a Java finally block should be avoided, illustrating how it suppresses exceptions and overrides earlier returns, and cites the Java Language Specification and JVM behavior to highlight the risks for developers.
The article, part of the "Fireline Decode" series, explains why using a return statement inside a finally block in Java should be avoided.
It shows an incorrect example where a method returns from finally, and demonstrates how this suppresses exceptions, using a second example with division by zero that unexpectedly returns a value instead of propagating the ArithmeticException.
public class Bar {
public String foo() {
try {
doSomething();
} catch (Exception e) {
throw e;
} finally {
return "OK"; // trigger rule
}
}
}The second example illustrates the problem:
public class Test02 {
public static void main(String[] args) {
int b = doSomething();
System.out.println("b=" + b);
}
public static int doSomething() {
int a = 10;
try {
a = 8 / 0;
} catch (ArithmeticException e) {
System.out.println("捕获到异常");
//e.printStackTrace();
throw e;
} finally {
return a; // wrong
}
//return a; // correct
}
}According to the Java Language Specification §14.20.2, if the finally block completes abruptly (e.g., with return), the reason from the catch block is discarded, and the try statement completes abruptly for the reason from finally.
- If the catch block completes abruptly for reason R, then the finally block is executed.
- If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).JVM documentation (section 3.13) further states that if a new value is thrown during finally execution, the finally aborts and the try‑catch‑finally construct returns abruptly with that new value.
If a new value is thrown during execution of the finally clause, the finally clause aborts, and tryCatchFinally returns abruptly, throwing the new value to its invoker.Therefore, a return or thrown exception in finally has the highest priority, causing any earlier return or exception from try or catch to be ignored, which can hide errors and make debugging difficult.
Advertisement for the Fireline product team follows.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.