Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions not propagating from a reflected method call in c#

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

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

The particular exception this method is raising is KeyNotFoundException, but that shouldn't matter because I'm catching everything right?

The particular error message I get from Visual Studio is

KeyNotFoundException was unhandled by user code

whereas normally the message would say

KeyNotFoundException was unhandled

if the call was not a reflected invocation.

I could just have the method check to see if they key is in there, and if not return null, but Using exception handling seems preferable. Is there any way to propagate exceptions up from a reflected method call?

like image 350
Lucina Avatar asked Nov 07 '11 19:11

Lucina


2 Answers

This could be an issue with the Visual Studio debugger as well. As noted in the accepted answer to this similar question here, there are a few workarounds that you can do. The simplest of which is changing your Visual Studio debugger to turn off "Just My Code" in Tools -> Options -> Debugging -> General. You can also wrap it in a delegate or explicitly try to catch the invocation exception and inspect the inner exception of that, which should be your KeyNotFoundException.

like image 75
Evan Phillips Avatar answered Oct 17 '22 04:10

Evan Phillips


It 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 do need to catch TargetInvocationException which is the exception thrown directly by Method.Invoke, wrapping the exception thrown by the method itself.

Can you come up with a similar short but complete program which demonstrates the problem?

like image 30
Jon Skeet Avatar answered Oct 17 '22 03:10

Jon Skeet