Reputation: 85
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
Upvotes: 3
Views: 1464
Reputation: 11
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;
}
Upvotes: 0
Reputation: 4177
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;
}
Upvotes: 8
Reputation: 203830
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.
Upvotes: 3