Video in progress
What does this method return, and why is writing return inside finally dangerous?
static int value() {
try {
return 1;
} finally {
return 2;
}
}
It returns 2. A return in finally overrides the value returned from try, and it even silently swallows an exception thrown inside try.
📖 Answer
The finally block runs no matter how try is exited. return 1 prepares the value, then finally runs and leaves with its own return 2.
It gets worse:
static int risky() {
try {
throw new IllegalStateException("muhim xato");
} finally {
return 0; // the exception disappears, and the caller knows nothing
}
}
Similarly, if a new exception is thrown inside finally, the original exception is lost too.
When finally doesn't run:
- when
System.exit()is called; - when the JVM crashes or the process is killed (
kill -9); - when the thread gets stuck in an infinite loop.
The rule: finally is only for releasing resources, so don't write return, break or throw in it. The IDE and Sonar flag this as an error right away. For resources, try-with-resources is better anyway.
Sign up to mark studied questions and save your progress.