假设您清理了一些资源,例如:这是 C#。
try{/*stuff*/}
catch(Exception e) {/*rollback logs etc.*/}
finally{
if( context.Transaction != null )
context.Transaction.Dispose();
context.Connection.Close();
context.Connection.Dispose();
}
这样做会更健壮吗?
try{/*stuff*/}
catch(Exception e) {/*rollback logs etc.*/}
finally{
try{
if( context.Transaction != null )
context.Transaction.Dispose();
}catch(Exception e){/*logs*/}
finally{
context.Connection.Close();
context.Connection.Dispose();
}
}
这样,如果 transaction.dispose 设法失败,至少连接将有机会关闭。
最佳答案
Would it be more robust to do this instead?
使用多个 using block 会更好。
首先,您的 catch block 将吃掉所有不需要的异常(可以 try ... finally 没有任何捕获)。仅当您可以处理异常(或增加异常值)时才使用 catch。
但更好:
using (var resA = GetMeAResourceNeedingCleanUp())
using (var resB = new AnotherResourceNeedingCleanUpn(...)) {
// Code that might throw goes in here.
}
注意。一旦异常回退,最终 block 被清理,抛出另一个异常可能会导致(充其量)混淆正在处理的对象。第二条准则:
不要从 Dispose 方法或终结器中抛出异常。如果您需要允许用户处理清理失败,请提供一个单独的 Close 方法,该方法可以报告其失败。
请注意,“框架设计指南”(第 2nd 版)将其作为 (§9.4.1):
AVOID throwing an exception from within Dispose(bool) except under critical situations where the containing process has been corrupted (leaks, inconsistent shared state, etc.).
关于c# - finally block 中的多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/573231/