Search code examples
c#exceptionattributesreturn-type

Is there a standard "never returns" attribute for C# functions?


I have one method that looks like this:

void throwException(string msg)
{
    throw new MyException(msg);
}

Now if I write

int foo(int x, y)
{
    if (y == 0)
        throwException("Doh!");
    else
        return x/y;
}

the compiler will complain about foo that "not all paths return a value".

Is there an attribute I can add to throwException to avoid that ? Something like:

[NeverReturns]
void throwException(string msg)
{
    throw new MyException(msg);
}

I'm afraid custom attributes won't do, because for my purpose I'd need the cooperation of the compiler.


Solution

  • No. I suggest you change the signature of your first function to return the exception rather than throw it, and leave the throw statement in your second function. That'll keep the compiler happy, and smells less bad as well.

    Edit: there is now a DoesNotReturn attribute that provides an alternative.