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

前端 未结 10 1663
青春惊慌失措
青春惊慌失措 2020-12-03 20:42

I have one method that looks like this:

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

Now if I write

         


        
10条回答
  •  既然无缘
    2020-12-03 21:23

    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'.");
        }
    }
    

提交回复
热议问题