Delegate.DynamicInvoke - catch exception

c#, delegates, exception

Solution

Oh yeah, and: I cannot use the exception type to decide! It is completely possible that the service itself throws a MemberAccessException as well, because it could do some delegate stuff itself...

Yes, you can use the exception type to decide. As mentioned in the documentation for `Delegate.DynamicInvoke`, if the method being called throws an exception (any exception), it will be wrapped in a `TargetInvocationException`. That is the exception you can catch, and you can then look at its `InnerException` property to know whether it's an exception you can deal with.

Problem

I'm calling a delegate (dynamically configurable service) using: ``` public void CallService (Delegate service, IContext ctx) { var serviceArgs = CreateServiceArguments(service, ctx); service.DynamicInvoke(serviceArgs); } ``` At this point I want to catch all exceptions that occurred in the called service method, however, I do not want to catch any exception that occurred due to the DynamicInvoke call. E.g.: - `service` delegate throws `DomainException` -> catch the exception - `DynamicInvoke()` throws `MemberAccessException` because the delegate is a private method -> do not catch the exception, let it bubble up I hope it is clear what I'm asking. How to decide whether a catched exception originates from the DynamicInvoke call itself or from the underlying delegate. Oh yeah, and: I cannot use the exception type to decide! It is completely possible that the service itself throws a MemberAccessException as well, because it could do some delegate stuff itself...

Original source