finally 块和 catch 块之后的代码清理之间的区别 (C#)
Difference between code cleanup in finally block and after catch block (C#)
在 finally 块中添加清理代码和在 catch 块之后添加清理代码有什么区别?
try
{
//some code
}
catch
{
}
finally
{
//cleanup
}
和
try
{
//some code
}
catch
{
}
//cleanup
如果您从 try .. catch
块中抛出一个未被此 catch
捕获的可抛出对象,finally
子句中的清理代码将执行,并且 finally
之后的代码将立即执行=11=] 块不会。
在第二种情况下,如果代码从 catch 块中重新抛出异常或 return,则不会调用您的 cleanup
代码。在 finally
块的情况下,即使您有异常或来自 catch 块的 return 语句,它也会被执行。
MSDN 说:
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur as a result of normal execution, of execution of a break,
continue, goto, or return statement, or of propagation of an exception
out of the try statement.
在 finally 块中添加清理代码和在 catch 块之后添加清理代码有什么区别?
try
{
//some code
}
catch
{
}
finally
{
//cleanup
}
和
try
{
//some code
}
catch
{
}
//cleanup
如果您从 try .. catch
块中抛出一个未被此 catch
捕获的可抛出对象,finally
子句中的清理代码将执行,并且 finally
之后的代码将立即执行=11=] 块不会。
在第二种情况下,如果代码从 catch 块中重新抛出异常或 return,则不会调用您的 cleanup
代码。在 finally
块的情况下,即使您有异常或来自 catch 块的 return 语句,它也会被执行。
MSDN 说:
By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block. Typically, the statements of a finally block run when control leaves a try statement. The transfer of control can occur as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.