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

前端 未结 10 1649
青春惊慌失措
青春惊慌失措 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:20

    You can indicate "never returns" by using generics to declare that the function returns "anything":

    T ThrowException(string msg)
    {
        throw new MyException(msg);
    }
    

    So now you can write:

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

    This idiom is used in languages like Haskell and F#, and is based on the principle of explosion, also known as "ex falso quodlibet". The reasoning is this: if a function never returns, then we can make whatever magical assumptions we want about its return value, since such value will never exist. Here, the caller (foo) assumes ThrowException will return an int.

    A few minor drawbacks:

    • The implementation of ThrowException can circumvent this by returning default(T).
    • You have to specify the return type when calling ThrowException (Haskell and F# can infer it).
    • This idiom is very uncommon in C#, so many people won't recognize it. You may have to add a comment saying what you're doing.

    As the other answers say, you're probably better off returning the exception rather than throwing it.

提交回复
热议问题