I'm working on a method which uses reflection to call another method. That "other method" can, however, throw an exception and I'd like to propagate that exception with it's original stack information and InnerException
. That is simply because the method that uses reflection is not supposed to handle the exception, the caller should.
Here's a simplified version of the code:
public static bool Test() {
try {
return (bool) typeof(Program).GetMethod("OtherMethod").Invoke(null, null);
} catch(TargetInvocationException ex) {
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
}
public static bool OtherMethod() {
throw new InvalidOperationException();
}
That code obviously won't compile, since the Test
method (according to the compiler) doesn't always return a value.
I could add a return false
after the ExceptionDispatchInfo.Capture
but I was wondering if there's a nicer way of achieving the same thing. Without writing the redundant return false
.
I know it's kind of a nitpick question, but I can't help wondering. Plus, redundant code gives me an itch :P
There is one other option: instead of adding a redundant return false;
you could add a redundant throw;
.
You then don't need to make up a return value. (OK, not a big deal for a bool
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With