从AppDomain.AssemblyLoad事件中抛出异常

The*_*man 5 .net c# exception

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

执行此操作时,输出如下:

Assembly ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null loaded
TestString
Done...
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我解释这种行为吗?谢谢.

编辑澄清一些事情:

  • 当我希望它运行时,程序集加载事件运行正常.但我的异常永远不会被抛出

  • 这是一个从较大的应用程序中提取的蒸馏示例.我想在装载后检查装配,如果我不喜欢它,我想快速失败......但是我的例外不会"发生"

Nic*_*oiu 1

您认为为什么没有抛出异常?如果它没有被抛出,人们会期望看到你的“永远不应该到达这里......”输出。但是,由于它不存在,因此可能会引发异常。

您的代码未捕获异常则完全是另一回事。引发 AppDomain.AssemblyLoad 事件的代码很可能正在捕获异常。