views:

112

answers:

4

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;
+2  A: 

There is no need to return a value atfter 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 new 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.

František Žiačik
+1  A: 

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;
}
rturrado
A: 

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

Padel
There's no `finally` in C++, and the question has no mention of catching the exception. And if the compiler is generating a warning due to not having a `return` after an unconditional `throw`, then the warning is bogus.
Mike Seymour
Very bad code for C++, we don't have `object`, `null`, or `new` all over the place...
Matthieu M.
It's actually C# but I think there's even a small level of similitude there...
Padel
A: 

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.

Daniel Trebbien