We have been discussing this topic today at work, and none of us could come up with a definitive answer about that question. Consider the following situation:
int foo()
{
int err;
err = some_call(1);
if (err != 0)
return err;
err = some_call(2);
if (err != 0)
return err;
err = some_call(3);
if (err != 0)
return err;
err = some_call(4);
if (err != 0)
return err;
bar();
return err;
}
There is a lot of code repetition. Obviously, this could be factorized with a macro, sadly not with a template (because of the return clause). Or at least not directly.
Now the question is, if we were to replace those return error codes with exceptions, and catching those exceptions right away, are compilers allowed and smart enough to detect the pattern and avoid throwing exceptions altogether ?
Here is an illustration of what I mean:
int foo()
{
try
{
// some_call now throws a ErrorReturned exception that contains the error code upon failure.
some_call(1);
some_call(2);
some_call(3);
some_call(4);
}
catch (ErrorReturned& ex)
{
return ex.error_code();
}
bar();
return 0;
}
Now, there is no current performance issue and so yes, we don't need to optimize or even care about that. This is more to understand what compilers are allowed to do.
In short so, is it a "good" practice and if so, can compilers optimize that by not throwing exceptions at all ? (Assuming the exception construction has no side effect)
See Question&Answers more detail:os