return statement should put beyond try/catch clause??

D

Dale King

Hello, Roedy Green !
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top