What if there is a return statement in finally block?

本文深入探讨了Java中try-catch-finally语句的执行机制,解析了在不同情况下(如正常返回、捕获异常及抛出新异常)finally块的执行时机。并通过具体代码示例,展示了当finally块中包含return语句时,如何影响异常的抛出过程。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值