在.NET中,为什么不能在抛出它的方法中捕获BadImageFormatException?

J S*_*ith 6 c# c++ exception visual-c++

当我声明一个在引用的Visual C++程序集中定义的Visual C++类型的变量时,我不会被引发的BadImageFormatException所吸引,因为我对这个异常未被catch子句捕获这一事实感到好奇.紧接着变量声明的try-catch语句,但是try-catch语句的catch子句围绕方法调用声明变量的方法.

    public static void method()
    {
        try
        {
            Some_Visual_Cpp_Type o;
        }
        catch (Exception)
        {
            Console.WriteLine("caught inside the method");//apparently not called
        }
    }
    public static void Main()
    {
        try
        {
            method();
        }
        catch (BadImageFormatException)
        {
            Console.WriteLine("caught outside the method");//prints "caught outside the method"
        }
    }
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下这种行为吗?

SLa*_*aks 7

当方法为JIT时,在其catch块存在之前抛出此异常.


Jar*_*Par 4

以@Slaks 答案为基础

在这种特殊情况下,导致 的项目BadImageFormatException确实位于方法内部,但这不一定是真的。如果Some_Visual_Cpp_Type将该值声明为参数怎么办?BadImageFormatException然后 catch 块将能够访问最初 导致 的值。

BadImageFormatException当可执行文件中的特定位置被确定为不可运行时,将引发该错误。JIT 不会尝试在方法中选择一个安全点来引发异常,而是完全放弃该方法。尝试解析该方法的好部分和坏部分几乎没有什么收获。对于 JIT 和开发人员来说,只需声明该方法完全错误并从那里继续前进就简单得多。

另请注意,不能保证BadImageFormatException在调用方法中可以捕获 。如果 JIT 决定内联到method内部Main,那么在调用时将抛出异常Main,因此在内部无法捕获