抛出异常后返回

Kri*_*ato 10 c++ exception return-value throw

在异常return之后,它对任何值都有益throw吗?如果没有,可以return省略语句,是否有可能删除编译器错误C4715: not all control paths return a value

提前致谢.

编辑:(示例代码)

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

return 0;
Run Code Online (Sandbox Code Playgroud)

Fra*_*čik 7

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;
Run Code Online (Sandbox Code Playgroud)

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.

  • MSVC将给出C4715:并非所有控制路径都返回代码中if路径的值,即使此路径因其始终抛出而无法返回. (3认同)