Why value is returned after finally block even it is inside try block in java?

时间:2016-04-04 18:44:17

标签: java

Here is code snippet which I am trying so far, inside experiment class below is the code.

public class experiment {
    public static void main(String args[]) {
        System.out.println(experiment.myMethod());  
    }

    public static int myMethod() {
        try {
            System.out.println("block");
            return 112;
        } finally {
            System.out.println("This is Finally block");
            System.out.println("Finally block ran even after return statement");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

Please, try formatting your code better next time.

According to Java documentation:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

The finally block