Please see the following code and explain the output behavior.
public class MyFinalTest { public int doMethod(){ try{ throw new Exception(); } catch(Exception ex){ return 5; } finally{ return 10; } } public static void main(String[] args) { MyFinalTest testEx = new MyFinalTest(); int rVal = testEx.doMethod(); System.out.println("The return Val : "+rVal); } }
The result is the return Val : 10.
Eclipse shows a warning: finally block does not complete normally
.
What happens to the return statement in catch block ?
Yes, we can write a return statement of the method in catch and finally block.
Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.
2) If finally block does not return a value then both try and catch blocks must return a value. If try-catch-finally blocks are returning a value according to above rules, then you should not keep any statements after finally block.
In a try-catch-finally block that has return statements, only the value from the finally block will be returned. When returning reference types, be aware of any updates being done on them in the finally block that could end up in unwanted results.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With