try-catch-finally with return after it

If all goes well, return inside the try is executed after executing the finally block.

If something goes wrong inside try, exception is caught and executed and then finally block is executed and then the return after that is executed.


public int Demo1()
    {
        try{
            System.out.println("TRY");
            throw new Exception();
            }catch(Exception e){
                System.out.println("CATCH");
            }finally{
                System.out.println("FINALLY");
            }return 0;

    }

the output of call to this method is like this

TRY
CATCH
FINALLY
0

Means Consider Try{}catch{}finally{} as sequence of statements executed one by one In this particular case. And than control goes to return.


The fact that the finally block is executed does not make the program forget you returned. If everything goes well, the code after the finally block won't be executed.

Here is an example that makes it clear:

public class Main {

    public static void main(String[] args) {
        System.out.println("Normal: " + testNormal());
        System.out.println("Exception: " + testException());
    }

    public static int testNormal() {
        try {
            // no exception
            return 0;
        } catch (Exception e) {
            System.out.println("[normal] Exception caught");
        } finally {
            System.out.println("[normal] Finally");
        }
        System.out.println("[normal] Rest of code");
        return -1;
    }

    public static int testException() {
        try {
            throw new Exception();
        } catch (Exception e) {
            System.out.println("[except] Exception caught");
        } finally {
            System.out.println("[except] Finally");
        }
        System.out.println("[except] Rest of code");
        return -1;
    }

}

Output:

[normal] Finally
Normal: 0
[except] Exception caught
[except] Finally
[except] Rest of code
Exception: -1

In that case the code inside the finally is run but the other return is skipped when there are no exceptions. You may also see this for yourself by logging something :)

Also see this concerning System.exit: How does Java's System.exit() work with try/catch/finally blocks?

And see returning from a finally: Returning from a finally block in Java