In Java, will the finally block not get executed if we insert a return statement inside the try block of a try-catch-finally ?
8 Answers
The finally block will always execute no matter if you return, or an exception is thrown within the try block.
See also section 14.19.2 Execution of try-catch-finally of the Java Language Specification
The finally block gets executed in all these cases. The point of executing finally block at the end is to allow you to release all the acquired resources.
Below is an example that shows how it works.
public class Hello {
public static void hello(){
try{
System.out.println("hi");
return;
}catch(RuntimeException e){
}finally{
System.out.println("finally");
}
}
public static void main(String[] args){
hello();
}
}
It gets executed even if you return inside the try block. I put one return statement inside try as well as one inside finally and the value returned was from finally, not from try.
public class HelloWorld{
public static void main(String args[]){
System.out.println(printSomething());
}
public static String printSomething(){
try{
return "tried";
} finally{
return "finally";
}
}
}
The output I got was "finally."
According to the official explanation:
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
I think it's a good idea that we should refer to the official website before we post an answer here.
finally
block will always get executed. That's why it's called finally :-) – homereturn
from a finally block. – Thilo