In .NET, why can't a BadImageFormatException be caught inside the method that throws it?

c#, c++, exception, visual-c++

Solution

Building on @Slaks answer

In this particular case the item causing the `BadImageFormatException` is indeed inside the method but that doesn't have to be true. What if the `Some_Visual_Cpp_Type` value was declared as a parameter instead? Then the catch block would have access to the value which caused the `BadImageFormatException` in the first place.

The `BadImageFormatException` is raised when a particular place in the executable is determined to be un-runnable. Instead of trying to pick a safe point in the method to throw the exception the JIT just abandons the method entirely. There is little to be gained by trying to parse apart the good parts of the method from the bad ones. It's much simpler to the JIT and developer to just declare the method altogether bad and move on from there.

Also note that it is not guaranteed that the `BadImageFormatException` is even catchable in the calling method. If the JIT decides to inline `method` inside of `Main` then the exception will be thrown when `Main` is called and hence uncatchable inside of there

Problem

I'm not intrigued by the BadImageFormatException that is thrown when I declare a variable of a Visual C++ type that is defined inside a referenced Visual C++ assembly as much as I am intrigued by the fact that the exception is not caught by the catch clause of the try-catch statement immediately surrounding the variable declaration, but by the catch clause of the try-catch statement surrounding the method call to the method that declares the variable. ``` 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" } } ``` Can someone please explain this behavior?

Original source