Return Statement in try catch and finally block

If you have a try catch finally block in java, the return statement behaves differently.
You may think
1. If I have a return in try then will finally block get called?
2. What if a exception occurs?
3. What if catch and finally both have return statements? which return will get executed?

lets see the below code block

In the test() method, we have return statements in try catch and finally block. Now if you call test() method you will see that first the System.out from try block will get printed and then the control shifts to finally block and System.out from finally block gets executed and the return statement from finally block gets executed and method return “3”.

Please note :

1. If a return statement is present in Finally block, then the return value in the finally block will override the return value in the try or catch blocks.
2. If no return statement in Finally block, then the statements in finally block are executed and then either try or catch block return statements (where the control was last before entering the finally block) is executed. (see example 2).

1. Example on return statement in try catch and finally block

Output

2. Example on return statement only in try

Output

When is Finally block not called?

The finally block will not be called after try or catch block in 2 scenarios
1. System.exit() is called
2. JVM crashes

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn