In Java, will the finally block no开发者_开发问答t get executed if we insert a return statement inside the try block of a try-catch-finally ?
The only time a finally
block will not be executed is when you call exit()
before finally
is reached. The exit()
call will shutdown the JVM, so no subsequent line of code will be run.
EDIT: This is not entirely correct. See the comments below for additional information.
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.
When ever a method tries to return to the caller, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.
If your finally block has a return, it will override any return in a try-catch block.Because of this "feature" a good practice is that finally block should never throw an exception or have a return statement.
If you call System.exit()
as someone else said, it will not be executed, but I believe it will also not be executed if there is an exception in the except block.
精彩评论