【发布时间】:2011-11-16 17:59:48
【问题描述】:
我正在编写一些代码,这些代码大量使用异常来处理某些错误条件(无论如何肯定不是最好的设计,但我正在使用它)。
当代码中发生异常时,我需要一种优雅的方式来清理任何打开的或临时的资源。
这可以这样执行:
try
{
foo();
bar();
}
catch (Exception)
{
// Oops, an error occurred - let's clean up resources
// Any attempt to cleanup non-existent resources will throw
// an exception, so let's wrap this in another try block
try
{
cleanupResourceFoo();
cleanupResourceBar();
}
catch
{
// A resource didn't exist - this is non-fatal so let's drop
// this exception
}
}
假设foo() 方法正确清理了自身,但bar() 方法抛出了异常。在清理代码中,我们将调用cleanupResourceFoo() first,它本身会抛出异常,因为foo 资源已经被清理了。
这意味着cleanupResourceBar() 最终不会被调用,我们最终会导致资源泄漏。
当然我们可以像这样重写内部的try/catch 块:
try
{
cleanupResourceFoo();
}
catch
{
}
try
{
cleanupResourceBar();
}
catch
{
}
但现在我们变得很丑。
我来自 C++ 背景,这是我通常会使用 RAII 来做的事情。关于在 C# 中处理此问题的优雅方式有什么建议吗?
【问题讨论】: