终结器总是由 .net 框架调用,因此序列可能会失控;即使构造函数失败,析构函数仍然可以被触发。
当此类终结器异常来自第三方库时,这可能会带来麻烦:我找不到处理它们的方法!
例如,在下面的代码中,虽然类 A 的构造函数总是抛出异常并失败,但 A 的终结器将由 .net 框架触发,并且由于 A 具有 B 类型的属性,所以调用 ~B()。
class Program // my code
{
static void Main(string[] args)
{
A objA;
try
{
objA = new A();
}
catch (Exception)
{
}
; // when A() throws an exception, objA is null
GC.Collect(); // however, this can force ~A() and ~B() to be called.
Console.ReadLine();
}
}
public class A // 3rd-party code
{
public B objB;
public A()
{
objB = new B(); // this will lead ~B() to be called.
throw new Exception("Exception in A()");
}
~A() // called by .net framework
{
throw new Exception("Exception in ~A()"); // bad coding but I can't modify
}
}
public class B // 3rd-party code
{
public B() { }
~B() // called by .net framework
{
throw new Exception("Exception in ~B()"); // bad coding but I can't modify
}
}
如果这些是我的代码,那就更容易了——我可以在终结器中使用 try-catch,至少我可以做一些日志记录——我可以允许异常使程序崩溃,尽快发现错误——或者如果我想“容忍”异常,我可以有一个 try-catch 来抑制异常,并有一个优雅的退出。
但是如果 A 和 B 是来自 3rd-party 库的类,我什么也做不了!我无法控制异常的发生,我无法捕获它们,所以我无法记录或抑制它!
我能做些什么?