开发者

C# Function cannot return -- prevent compiler warning

I have a function that is guaranteed never to return. It logs data and throws an exception.

public int f()
{
    ... do stuff ...
    if(condition)
        BadUserData.Throw(... parameters...);
    else
        return 0;
}

I get the error message "not all code paths return a va开发者_如何学JAVAlue. I can fix this of course by a dummy return after the non returning function, but I wonder if there is an attribute or something I can apply to the Throw function it indicate that it never returns? I had a look and could not find one.


No, there isn't. Actually, to get the most appropriate call stack, I would have something more like below, where the method creates the exception but we throw it locally:

if(condition)
    throw BadUserData.CreateSomeFormOfException(... parameters...);

which solves both problems in one go.

Another lazier approach would be:

if(condition) {
    // throws <===== comments are important here ;p
    BadUserData.Throw(... parameters...);
}
return 0;


Well instead of BadUserData.Throw actually throw:

public int f()
{
    ... do stuff ...
    if(condition)
        throw new Exception("... parameters...");
    else
        return 0;
}

or have this method return an Exception and then:

throw BadUserData(... parameters...);

Other than that, no, there aren't any attributes or anything that will make your code to compile.


If the method's job is to log and then throw and exception, you sould change the method signature to be

public void f() 

instead of

public int f()

This will take care of your compiler issue. It's also going to be a lot cleaner as you can omit the else section of the method body.


Return the exception in BadUserData.Throw instead of throwing it and do:

public int f()
{
    ... do stuff ...
    if(condition)
        throw BadUserData.Throw(... parameters...);
    else
        return 0;
}


I guess you have no other choice than adding a return statement with a dummy value, e.g. return -1;.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜