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

Why not just change it to

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

This gives the same runtime results, and the compiler won't complain.


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.


Bernhof's answer is correct. However, if you are trying to encapsulate a large chunk of logic when instantiating your exception, then all you need to do is change your code from this:

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

to this:

Exception makeException(string msg) {
    return new MyException(msg);
}

Then your calling code will look like this:

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

All other things being equal, prefer functional code to procedural code. It's easier to re-use and unit-test.

EDIT:

In light of Fred's sample code, this is what I would do. It's not a code contract, but it's still functional.

private int getVarID(string s_varID) {
    int varID;
    if(s_varID == "ILT") {
        return 123;
    } else if(s_varID == "TL") {
        return 456;
    } else if(s_varID == "FT") {
        return 789;
    } else if(int.TryParse(s_varID, out varID)) {
        return varID;
    } else {
        throw makeParseError("varID must be an integer or 'ILT', 'TL' or 'FT'.");
    }
}