开发者

Why code in finally will execute even it has returned in try block?

Code:

public String g开发者_运维知识库et() {
try {
     //doSomething
     return "Hello";
}
finally {
     System.out.print("Finally");
}

How does this code execute?


Because that's the whole point of a finally block - it executes however you leave the try block, unless the VM itself is shut down abruptly.

Typically finally blocks are used to clean up resources - you wouldn't want to leave a file handle open just because you returned during the try block, would you? Now you could put that clean-up code just before the return statement - but then it wouldn't be cleaned up if the code threw an exception instead. With finally, the clean-up code executes however you leave the block, which is generally what you want.

See JLS section 14.20.2 for more details - and note how all paths involve the finally block executing.


Finally ALWAYS gets executed, no matter what happens in the try block (fail, return, exception, finish etc.).

If you don't want this code to be executed, you could always placed it after the try/catch/finally statement.


That's exactly what finally is for: the code inside will execute when the try block is left, no matter how (except the JVM shutting down via System.exit() or external reasons).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜