D
Dale King
Hello, Roedy Green !
While a return in finally is allowed it should most certainly be
avoided and is frowned upon. It leads to confusing code. Consider
this code:
try
{
someCode();
return 1;
}
catch( AnException e )
{
throw something;
}
finally
{
return 0;
}
Does this code return 0 or 1 when there is no exception? If the
exception is thrown does the something exception really reach the
caller or does the return in the finally override the exception?
How do the answers change with different combinations of return
and throw?
There are definite answers to these questions, but I bet many
programmers could not tell you the answer with confidence. And
there has probably been at least one version of some compiler got
it wrong, so it is probably not be wise to rely on it.
You said:you can do it both ways.
If you have the return inside the try you must provide either a throw
or anther return in the catch, after the catch or in a finally. There
must be a route to return whether there is an exception or not.
While a return in finally is allowed it should most certainly be
avoided and is frowned upon. It leads to confusing code. Consider
this code:
try
{
someCode();
return 1;
}
catch( AnException e )
{
throw something;
}
finally
{
return 0;
}
Does this code return 0 or 1 when there is no exception? If the
exception is thrown does the something exception really reach the
caller or does the return in the finally override the exception?
How do the answers change with different combinations of return
and throw?
There are definite answers to these questions, but I bet many
programmers could not tell you the answer with confidence. And
there has probably been at least one version of some compiler got
it wrong, so it is probably not be wise to rely on it.