Returning after throwing exceptions

Kristian D'Amato picture Kristian D'Amato · Jun 24, 2010 · Viewed 8.7k times · Source

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;

Answer

František Žiačik picture František Žiačik · Jun 24, 2010

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.