3

Im using reflection to invoke a method which throws a exception. But this exception is not thrown, neigter i can catch it.
Im invoking by calling:

GetMethod().Invoke(myInstance, new object[] { result });

Where result is of type Object. The called method throws a exception like:

public async Task MyMethod(Object input)
    {
        // do something...
        throw new Exception("Error");

    }

If i dont use a try-catch block, the application continuous as well as if i use one like:

try
{
    GetMethod().Invoke(myInstance, new object[] { result });
    log("everything is ok");
}
catch(Exception e)
{
    log(e.message) 
}

So the expected output should be:

Error

but is

everything is ok

2

3 Answers 3

8

Your method returns a Task, so does not actually throw an exception. In order to get the exception, you should unwrap the task first:

var result = GetMethod().Invoke(myInstance, new object[] { result });
if (result is Task task)
{
    // this line will throw.
    await task;
}
0
3

MyMethod doesn't throw an exception. It returns a Task that will eventually be in a faulted state. You can access the members of that task (when it has completed) to see that it resulted in an exception, but calling MyMethod will never throw an exception because it's an async method. It will only ever return a Task in one state or another.

0
0

I faced This issue and I did this which will work 100%, Try taking the result as dynamic and check for Exception as follows:-

dynamic res = GetMethod().Invoke(myInstance, new object[] { result });
            if (res.Exception != null)
            {
                throw res.Exception;
            }

Not the answer you're looking for? Browse other questions tagged or ask your own question.