Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

exception - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...