Re: try catch finally misbehaving
Mark Smith wrote:
public static String testFunc()
{
String outcome="FAILED";
Object nullRef=null;
try
{
nullRef.toString();
if(false)
{
throw new SQLException();
}
outcome="SUCCESS";
}
catch (SQLException e)
{
outcome="SQLException";
}
finally
{
return outcome;
}
}
When do you expect the outcome to be thrown? The finally block is more
or less implemented as follows:
Execute try
If caught error, process appropriate catch block
goto finally code [1]
execute finally code
return to original position
continue executing code.
It also works by implementing a catch-all handler which will catch the
exception, run finally, and then rethrow it.
BUT--your finally code doesn't finish, because it returns the outcome.
How is it supposed to go back and throw the exception after it returns
the value?
[1] To be fair, this is a better description for the implementation from
Java 1.0 - Java 1.4, inclusive, and theoretically in Java 1.5. In Java
1.5 (though not publicized until Java 1.6), the implementation was
changed to avoid the jsr and ret instructions in favor of inlining the
code at every point of execution. The old implementation is clearer for
illustration purposes, if you ask me.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth