Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled exception in try/catch block

Tags:

c#

exception

This one is really baking my noodle...

I've got some code. When I run it, Visual Studio complains about an unhandled exception. And, sure enough, there is an exception. However, it's blatently inside a try/catch block, so... how is that "unhandled"??

I've searched around, and the only relevant hit I can find is related to LINQ. But I'm not using any LINQ, so that can't be it.

The relevant code looks something like this:

try
{
  method.Invoke(target, new object[0]);
}
catch (MyException e)
{
  Console.WriteLine(e);
}

The method being hit by Invoke() is different every time. Some of these methods really do throw exceptions - which is fine. But that's why I put it in a try-block! I don't understand why VS is complaining that the exception isn't handled.

(Yes, I have checked that the exception being thrown is a MyException object.)

At this point, my only guess is that it's somehow related to using reflection. I really need to fix this though... Any suggestions?

like image 960
MathematicalOrchid Avatar asked Dec 17 '25 17:12

MathematicalOrchid


1 Answers

You should read the documentation for MethodInfo.Invoke.

Exceptions

TargetInvocationException - The invoked method or constructor throws an exception.

Remarks

If the invoked method throws an exception, the Exception.GetBaseException method returns the exception.

Your exception is being wrapped in a TargetInvocationException.

like image 90
Sam Harwell Avatar answered Dec 19 '25 10:12

Sam Harwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!