views:

134

answers:

2

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?

A: 

If there is a situation, where the TargetInvocationException can be thrown without the invoked method throwing and exception, it makes sense. I'm not sure if there's such a case.

Slavo
+5  A: 

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.

ewernli
But of course! `Invoke` can throw itself, and so can the invoked method, and you need to distinguish the two. Thanks!
romkyns