vendredi 30 janvier 2015

Getting "not all code paths return a value" when using ExceptionDispatchInfo.Capture

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 {
bool returnValueOfInvoke = false;
typeof(Program).GetMethod("OtherMethod").Invoke(null, null);
return returnValueOfInvoke;
} catch(TargetInvocationException ex) {
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
}

public static void 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






Aucun commentaire:

Enregistrer un commentaire