finally块抛异常或者包含return语句时的注意事项

先看两段代码,请试着分别写出它们的输出结果。

 

1、try-catch 块与 finally 块同时抛异常。

 

import java.io.IOException;
public class ExceptionInFinallyBlock {
    public static void main(String[] args) {
        try {
            try {
                System.out.print("A");
                throw new Exception("1");
            } catch(Exception e) {
                System.out.print("B");
                throw new Exception("2");
            } finally {
                System.out.print("C");
                throw new IOException("3");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

 

 

2、try-catch 块与 finally 块同时包含 return 语句。

 

public class ReturnStatementInFinallyBlockTest {
    public static void main(String[] args) {
        System.out.println(getReturnValue());
    }
    public static int getReturnValue() {
        try {
             System.out.print("A");
             return 1;
        } finally {
            System.out.print("C");
            return 2;
        }
    }
}

 

 

Java标准文档中给出了详细的描述,可以用一句话简单概括上面两个示例执行逻辑:

  • 在 finally 块中抛出的任何异常都会覆盖掉在其前面由 try 或者 catch 块抛出异常。包含 return 语句的情形相似。

鉴于此,除必要情况下,应该尽量避免在 finally 块中抛异常或者包含 return 语句

 

PS: 实际上,当你把上面两段代码拷贝到 eclipse,会收到 eclipse 的 warning: finally block does not complete normally。

 

 

----------------

输出结果:

1、ABC3

2、AC2

 

本文总结自:SO

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值