Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 1000
Kristian D'Amato Avatar asked Jun 24 '10 12:06

Kristian D'Amato


People also ask

Can you return after throwing an exception Java?

Can you return after a throw? After you call throw the method will return immediately and no code following it will be executed. This is also true if any exceptions are thrown and not caught in a try / catch block.

How do you continue after throwing an exception?

Resuming the program When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.

Is throwing an exception the same as returning a value?

For example Note that throwing an exception means that the method was used wrong or had an internal error, while returning an exception means that the error code was identified successfully.


1 Answers

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.

like image 99
František Žiačik Avatar answered Sep 23 '22 17:09

František Žiačik