天天看点

【火线解码】001.避免在finally语句块中使用return语句

火线团队推出【火线解码】系列文章,每一篇解释一种不规范的代码写法,用较短的篇幅让大家快速的了解代码规范问题。

001.避免在finally语句块中使用return语句

错误的代码示例:

public class Bar {
   public String foo() {
        try {
            doSomething();
        } catch (Exception e) {
            throw e;
        } finally {
            return "OK"; //触发规则
        }
    }
}
           

以上代码中的try-catch-finally是Java代码中很常见的写法,其中finally语句块作为确定会执行的语句块,一般多用于资源的清理操作。但是文中的finally语句块中使用了return语句,是需要避免的写法。

为什么?

举例说明:

public class Test02 {
    public static void main(String[] args) {
          int b=doSomething();
          System.out.println("b="+b);
      }

    public static int doSomething() {
        int a = ;
        try {
             a= /;
        } catch (ArithmeticException e) {
            System.out.println("捕获到异常");
            //e.printStackTrace();
            throw e;
        } finally {
            return a;//错误的写法
        }
        //return a;//正确的写法
    }
}
           

代码中在doSomething()方法中设置了一个常见的除0异常。当执行main方法时,我们预期应该输出“捕获到异常”,并抛出异常的详细信息。

实际该代码输出了“捕获到异常”以及“b=10”,没有抛出异常信息。根据输出信息“捕获到异常”语句说明try-catch语句块实际已经执行完成,但是输出“b=10”说明程序并没有认为doSomething()方法抛出了异常,为什么呢?

根据Java语言规范文档14.20.2,

- If the catch block completes abruptly for reason R, then the finally block is executed. 
    - If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
           

翻译:

在一个try-catch-finally语句中,如果catch语句块由于原因R立即结束,例如return或者出现异常,那么会继续执行finally语句块。

当finally语句块由于原因S立即结束,例如使用了return语句或者出现异常,那么try语句也会由于原因S立即结束,并且之前造成catch语句块立即结束的原因R(出现异常)会被丢弃。

在JVM层面,根据JVM文档3.13. Compiling finally,

If a new value is thrown during execution of the finally clause, the finally clause aborts, and tryCatchFinally returns abruptly, throwing the new value to its invoker.
           

翻译:

如果finally子句在执行期间抛出一个新值,finally子句中止,整个try-catch-finally语句块立即返回,将这个新值抛给上层调用者。

总结

在try-catch-finally语句块中,finally语句块中的return/抛出异常(立即结束语句)的优先级最高,程序会优先返回finally语句块中的立即结束语句的结果,此时try-catch语句块中的return/抛出异常(立即结束语句)的结果就会被丢弃掉。

所以我们在将捕获的异常抛出给调用的上层方法处理时,如果被finally语句块中的return语句覆盖掉了,那么这个导致异常的错误情况将很难发现和定位。

广告

【火线解码】系列文章由专注于安卓代码扫描的火线产品团队提供,火线官网:http://magic.360.cn

—— 用火线,守住代码底线!

继续阅读