Search code examples
c++exceptionreturn-valuethrow

Returning after throwing exceptions


Is it in any way beneficial to return a value after throwing an exception? If not, can the return statement be 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;

Solution

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