What if there is a return statement in finally block?

In normal situation this is how we use the try-catch-finally statement:

try {
    //Code
}catch (Exception e) {
    //Handle the exceptional case
}finally {
    //Clean up code to be executed no matter there are exceptions
}

This is how I understand how JVM execute the statements. 

1. If try block completes normally with a return statement, the finally block will be executed before executing the return statement in try block.

2. If try block completes aburptly with an exception that could be catched by the catch block, catch block will be executed. In this case:

2.1 If the catch block completes normally with a return statement, the finally block will be executed before executing the return statement in catch block

2.2 If the catch block completes aburptly with an exception, finally block will be executed before throwing a new exception in catch block.

 

Base on the assumption, that explains why the throw statement is not executed in catch block:

package com.ricardo.test.trycatchblock;

public class Test {

    public static void main(String[] args) {
        System.out.println(getResult(0));
    }

    public static int getResult(int b) {
        int result = -1;
        try {
            result = 100 / b;
        }catch (ArithmeticException e) {
            result = -2;
            throw new RuntimeException("Ricardo defined Exception");
        }finally {
            return result;
        }
    }
}

When there is an ArithmeticException thrown in the try block, the catch block is executed. When it reaches the throw statement, JVM starts executing the finally block before throw a "Ricardo defined Exception" RuntimeException.  However, the return statement in finally block directly return the value to main method, so eventually the throw statement is not executed.

If I move the return statement out of finally block,

package com.ricardo.test.trycatchblock;

public class Test {

    public static void main(String[] args) {
        System.out.println(getResult(0));
    }

    public static int getResult(int b) {
        int result = -1;
        try {
            result = 100 / b;
        }catch (ArithmeticException e) {
            result = -2;
            throw new RuntimeException("Ricardo defined Exception");
        }finally {

        }
        return result;
    }
}

the exception can be thrown. Also if you are using intellij, there is a hint as below:

Reference:

 Java Language Specification: https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2

猜你喜欢

转载自blog.csdn.net/yes1234500/article/details/82828693