从AppDomain.AssemblyLoad事件抛出异常抛出、异常、事件、AppDomain

2023-09-04 10:19:49 作者:深碍你、久绊你

有人能向我解释为什么我似乎无法从AppDomain.Assembly负载事件中抛出异常?例如:

Can someone explain to me why I cannot seem to throw an exception from inside the AppDomain.Assembly load event? For example:

class Program
{
    static Program()
    {
        AppDomain.CurrentDomain.UnhandledException += (s, a) =>
        {
            Console.WriteLine("Caught exception!");
        };

        AppDomain.CurrentDomain.AssemblyLoad += (s, a) =>
        {
            Console.WriteLine(string.Format("Assembly {0} loaded", a.LoadedAssembly.FullName));

            throw new Exception();

            Console.WriteLine("Should never get here...");
        };
    }

    static void Main(string[] args)
    {
        Console.WriteLine(new ClassLibrary1.Class1().TestString());
        Console.WriteLine();
        Console.WriteLine("Done...");
        Console.ReadLine();
    }
}

当我执行此,输出如下:

When I execute this, the output is as follows:

Assembly ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null loaded
TestString
Done...

任何人都可以解释这种现象给我?谢谢你。

Can anyone explain this behavior to me? Thank you.

修改:要澄清两件事情:

该组件加载事件运行正常,当我希望它运行。但我的异常永远不会被抛出

The assembly load event runs fine, when I expect it to run. But my exception never gets thrown

这是从一个较大的应用程序所采取的一种蒸馏的例子。我要检查的程序集加载后,如果我不喜欢的东西吧,我想快速失败......但是我的异常不会发生

This is a distilled example taken from a larger application. I want to inspect the assembly after it is loaded and if I don't like something about it, I want to fail fast... But my exception doesn't 'happen'

推荐答案

为什么你认为这个异常没有被抛出?如果没有被抛出,人们会希望看到你的不应该到这里来......输出。但是,由于它不存在,除了presumably被抛出。

Why do you think the exception is not being thrown? If it weren't being thrown, one would expected to see your "Should never get here..." output. However, since it's not there, the exception presumably is being thrown.

您code没有的捕的异常是完全是另外一个故事。这很可能是code引发的AppDomain.AssemblyLoad事件是捕捉异常。

Your code not catching the exception is a whole other story. It's quite possible that the code that raises the AppDomain.AssemblyLoad event is catching exceptions.