Does finally always execute in Java?
I have a try/catch block with returns inside it. Will the finally block be called?
For example:
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("i don't know if this will get printed out.");
}
I know I can just type this in an see what happens (which is what I'm about to do, actually) but when I googled for answers nothing came up, so I figured I'd throw this up as a question.
Java
return
try-catch-finally
- asked 9 years ago
- B Butts
2Answer
finally
will be called.
The only times finally
won't be called are:
- if you call
System.exit()
or - another thread interrupts current one (via the
interrupt
method) or - if the JVM crashes first
- answered 8 years ago
- Sandy Hook
//proof code
class Test
{
public static void main(String args[])
{
System.out.println(Test.test());
}
public static int test()
{
try {
return 0;
}
finally {
System.out.println("finally trumps return.");
}
}
}
output:
finally trumps return.
0
- answered 8 years ago
- Sunny Solu
Your Answer