I have the following piece of code.
public static void main(String[] args) {
System.out.println(returnString());
}
private static String returnString(){
In Java, the code:
try {
if (foo()) return 1;
} catch (Exception e){
if (goo()) return 2;
} finally {
if (moo()) return 3;
}
will rewritten by the compiler into:
try {
if (foo())
{
if (moo()) return 3; // Finally code executed before return
return 1;
}
} catch (Exception e){
if (goo())
{
if (moo()) return 3; // Finally code executed before return
return 2;
}
} catch (Throwable e){
if (moo()) return 3; // Finally code executed before re-throw
throw e;
}
if (moo()) return 3; // Finally code executed before leaving block
Basically, the compiler will duplicate the code in the finally
block exactly once in every execution path that would cause code execution to leave the guarded block, whether via return
, throw
, or fall-through. Note that while some languages disallow a return
within a finally
block, Java does not; if a finally
block is executed as a consequence of an exception, however, a return
within the block may cause the exception to get silently abandoned (look at the code above marked "Finally code executed before re-throw"; if the return 3;
executes, the re-throw will get skipped).