在支持异常的编程语言中,通常需要使用 try-catch-finally 结构捕获异常并进行处理。此时有人会问:finally 块中的语句放在 try-catch 结构的外部同样会执行,为什么还需要 finally 呢?
高赞回答对这个事情是这样解释的:
finally 块存在的目的是为了确保在出现如下三种情况时,块内的代码能够被执行(仅使用 catch 块无法确保这些情况下能够执行这部分代码)
- try 块中的代码尝试使用 return 语句退出执行
- catch 块中的代码重新抛出了已捕获的异常,或是故意或无意地抛出了新的异常
- try 块中的代码遇到了一个没有被 catch 语句捕获的异常
问题原文如下:
I have used try-catch/except-finally variants in many languages for years, today someone asked me what is the point of finally and I couldn't answer.
Basically why would you put a statement in finally instead of just putting it after the whole try-catch block? Or in other words is there a difference between the following blocks of code:
try{ //a}
catch {//b}
finally {//c}
try{//a}
catch{//b}
//c
EDIT:
PEOPLE, I know what finally does, I have been using it for ages, but my question is in the above example putting //c in finally seems redundant, doesn't it?
回答原文如下:
The purpose of a finally block is to ensure that code gets run in three circumstances which would not very cleanly be handled using "catch" blocks alone:
- If code within the try block exits via return
- If code within a catch block either rethrows the caught exception, or--accidentally or intentionally--ends up throwing a new one.
- If the code within the try block encounters an exception which for which the try has no catch.
One could copy the finally code before every return or throw, and wrap catch blocks within their own try/catch to allow for the possibility of an accidental exception occurring, but it's far easier to forgo all that and simply use a finally block.
BTW, one thing I wish language designers would include would be an exception argument to the finally block, to deal with the case where one needs to clean up after an exception but still wants it to percolate up the call stack (e.g. one could wrap the code for a constructor in such a construct, and Dispose the object under construction if the constructor was going to exit with an exception).
很有意义的一个问题,遂于此记录。