开发者

Returning after throwing exceptions

Is it in any way beneficial to return a value after throwing an exception? If not, can the return statement 开发者_如何学Pythonbe left out and is it somehow possible to remove compiler error C4715: not all control paths return a value?

Thanks in advance.

Edit: (sample code)

for (ushort i = 0; i < itsNumUnits; ++i)
    if (unitFormation[i] == unit)
    {
        return unitSetup[i];
    }
    else
        throw unit;

return 0;


There is no need to return a value after exception throw. If you have this error, you should check the paths your code can get to without throwing an exception, e.g.

if (something)
    throw Exception;
else
    return value;

Failing to return value in the "else" branch of "if" would cause a compile error because the exception may or may not be thrown depending on value of something.


throw itself terminates the function execution. But if your function returns a value, and the exception is not thrown, you'll have to take care of returning a value. E.g.:

bool foo(bool _flag) throw(...)
{
    if (_flag)
    {
        throw "foo is throwing an exception";
    }
    return true;
}


The closest equivalent to being able to "return" a value as well as throw an exception is when the function writes to a pointer or referenced object before throwing the exception:

void my_func(int& ret)
{
    ret = 0;

    for (ushort i = 0; i < itsNumUnits; ++i) {
        if (unitFormation[i] == unit) {
            ret = unitSetup[i];
            return;
        }
        else {
            throw unit;
        }
    }
}

This pattern, however, is error-prone and rarely useful. Think carefully before using it.


After throw you end up in catch (the code below throw is not executed). The only block that is executed is the finally.

If you want to achieve something like what you described above go for something like this:

object returnVal = null; // the bad
try
{
    //some code here
    throw new Exception(); // something bad happened
    //some more code
    returnVal = new object(); // the good
}
catch(Exception ex)
{
    // log, try to recover etc.
    // maybe it`s a good idea not to throw it away if you can handle it here!
}
return returnVal; // either the good or the bad (never the ugly!)

The C# equivalent of the warning is a compiler error so in any way I don't think a good idea is to get rid of compiler warnings but to try to solve them.

Regards...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜