Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of return statement in catch and finally

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 ?

like image 725
Ammu Avatar asked Apr 18 '11 10:04

Ammu


People also ask

Can we have a return statement in try catch and finally block?

Yes, we can write a return statement of the method in catch and finally block.

Is finally executed if return in catch?

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.

What happens if both a catch and a finally block define return statement?

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.

How do you handle a return statement in try catch?

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.


1 Answers

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"

like image 135
Bozho Avatar answered Sep 22 '22 18:09

Bozho