Java – why does the code in finally execute even if it is returned in a try block?

Code:

public String get() {
try {
     //doSomething
     return "Hello";
}
finally {
     System.out.print("Finally");
}

How does this code execute?

Solution

Because this is the focus of the finally block - it will execute, but you will leave the try block unless the VM itself suddenly shuts down

Typically, a finally block is used to clean up resources – you don't want to keep the file handle open because you return during a try block, do you? Now you can put cleanup code before the return statement - but if the code throws an exception, it won't be cleared Finally, the cleanup code will execute, but you will leave the block, which is usually what you want

Refer to JLS section 14.20 for more details 2 - and note how all paths involve finally block execution

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>