`
wxl24life
  • 浏览: 290732 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

    博客分类:
  • Java
阅读更多

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

 

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

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics