Please see the following code and explain the output behavior.
public class MyFinalTest {
public int doMethod(){
try{
throw new Exce
finally
is always executed (the only exception is System.exit()
). You can think of this behavior this way:
finally block will always execute (only exception is it encounters System.exit() anywhere before it), so simply the 5 is replaced (overridden) by 10 before returning by finally block
The finally
block is always executed (if the matching try was executed) so before the method returns 5 as in the catch
block, it executes the finally
block and returns 10.
the finally section will execute always execute. e.g. if you have any thing to release, or log out sort of thing, if error occur then go to catch section else finally will execute.
Session session // opened some session
try
{
// some error
}
catch { log.error }
finally
{ session.logout();}
it should not used to return anything. you can use outside of.
In a nut shell, we could say finally block dominates return statement, irrespective of, if return present in try or catch block.
Always finally dominates in that use case.
public static int m1() {
try {
return 100;
}
catch(Exception e)
{
return 101;
}
finally {
return 102;
}
}
Output - 102
It is overridden by the one in finally
, because finally
is executed after everything else.
That's why, a rule of thumb - never return from finally
. Eclipse, for example, shows a warnings for that snippet: "finally block does not complete normally"