Exceptions not propagating from a reflected method call in C #

When calling a method using methodInfo.Invoke, if an exception is thrown, it does not propagate to my catch blocks.

object value; try { value = myMethod.Invoke(null, parameters);//program crashes with uncaught exception } catch { throw new Exception("Caught!");//never executed } 

A special exception thrown by this method is a KeyNotFoundException, but it does not matter because I understand everything well?

The specific error message I get from Visual Studio is

 KeyNotFoundException was unhandled by user code 

whereas as usual the message will be

 KeyNotFoundException was unhandled 

if the call was not a reflected call.

I could just check the method to see if they have a key, and if not returning null, but using exception handling seems preferable. Is there a way to throw exceptions from the call to the reflected method?

+7
source share
3 answers

This can be a problem for the Visual Studio debugger. As noted in the accepted answer to this similar question here , you can make some workarounds. The simplest of which is changing the Visual Studio debugger to disable "Only my code" in "Tools" → "Options" → "Debugging" → "General". You can also wrap it in a delegate or explicitly try to catch a call exception and check for an internal exception, which should be your KeyNotFoundException.

+3
source

This works for me:

 using System; using System.Reflection; class Program { static void Main(string[] args) { var method = typeof(Program).GetMethod("ThrowException"); try { method.Invoke(null, null); } catch (TargetInvocationException e) { Console.WriteLine("Caught exception: {0}", e.InnerException); } } public static void ThrowException() { throw new Exception("Bang!"); } } 

Note that you need to catch a TargetInvocationException , which is an exception thrown directly by Method.Invoke , which Method.Invoke exception thrown by the method itself.

Can you find a similar short but complete program that demonstrates the problem?

+3
source

If an error occurs during a method called with reflection, it should throw a TargetInvocationException , which wraps (via .InnerException ) the original. However, there are several methods that can lead to the failure of more terminals, for example, several methods for creating a winform / message loop.

It is also possible that this method works, but causes additional work in another thread, and it that does not work. This will kill the stream, and you cannot catch it, since it is not on your stream. This would be especially likely if your code is actually in the workflow.

+1
source

All Articles