Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MethodInfo.Invoke wrap exceptions in a TargetInvocationException?

I'm asking this out of curiosity rather than due to a real need to know, but I can't think of any good reasons for MethodInfo.Invoke to wrap its exceptions.

Were it to let them pass unwrapped, debugging such exceptions in Visual Studio would be a tiny bit easier - I wouldn't have to ask VS to stop on first-chance exceptions to see the current state at the source of exception. The stack trace would presumably show [external code] just after the call to Invoke, but so what.

Am I missing some important function that this wrapping provides that would not be possible had Invoke let exceptions pass unwrapped?

like image 450
Roman Starkov Avatar asked Mar 03 '10 12:03

Roman Starkov


1 Answers

Am I missing some important function that this wrapping provides that would not be possible had Invoke let exceptions pass unwrapped?

Yes. One argument is to be able to distinguish between exception throw by the target method and exception thrown by the reflection mechanism itself. Ex. the ArgumentException can be thrown from the reflection mechanism or the target method -- these are two different meta-level.

Another argument is the contract of the invoke method itself. In Java, the invoke method is allowed to throw only the exception declared in the method signature. Arbitrary exception would simply not obey the signature and need then to be wrapped. This argument doesn't hold for C# as is, but is still valid. The invoke method has a contract defined in the doc which you could not rely on, if target exception were thrown as is.

like image 180
ewernli Avatar answered Nov 16 '22 03:11

ewernli