c#:如何处理来自第三方库的终结者例外?

ath*_*hos 10 c# exception finalizer

终结器总是被.net框架调用,因此序列可能失控; 即使构造函数失败,仍然可以触发析构函数.

当这样的终结者例外来自第三方库时,这可能带来麻烦:我找不到处理它们的方法!

例如,在下面的代码中,尽管A类的构造函数总是抛出异常而失败,但是A的终结符将由.net框架触发,同时~B()被调用为A具有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
    } 
}
Run Code Online (Sandbox Code Playgroud)

如果这些是我的代码,它会更容易一些 - 我可以在终结器中使用try-catch,至少我可以做一些日志记录 - 我可以允许异常崩溃程序,尽快发现错误 - 或者如果我想"容忍"异常,我可以有一个try-catch来抑制异常,并有一个优雅的退出.

但如果A和B是来自第三方库的课程,我什么也做不了!我无法控制异常发生,我无法捕捉它们,所以我无法记录或压制它!

我能做什么?

Cod*_*ike 2

听起来第 3 方实用程序写得不好。:)

您是否尝试过使用AppDomain.UnhandledException捕获它?