Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

reflection

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

like image 347
Vincent Avatar asked Sep 04 '25 01:09

Vincent


1 Answers

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)

like image 58
Henrik Avatar answered Sep 07 '25 11:09

Henrik