作为一名Java开发者,拥有扎实的Java基础才能立于不败之地,比如面试或者被面试等等情况。在某些情况下Java的语法极具迷惑性也就是所谓的“坑”比如finally和return语句最终返回谁的结果?,那么本篇将总结一下Java中finally和return的优先级。
代码
package com.github.xuchengen.other; /** * 最终返回实例 * 作者:徐承恩 * 邮箱:xuchengen@gmail.com * 日期:2019/11/4 */ public class FinallyReturnExample { public static void main(String[] args) { System.out.println(finallyReturn1()); System.out.println(finallyReturn2()); } private static String finallyReturn1() { try { throw new RuntimeException(); } catch (Exception e) { return "catch"; } finally { return "finally"; } } private static int finallyReturn2() { int a = 1; try { return a; } catch (Exception e) { a = -1; } finally { a = 30; System.out.println(a); } return a; } }
finallyReturn1函数最终执行结果为:finally
finallyReturn2函数最终执行结果为:打印30,函数返回1
上述问题的本质就是在try、catch、finally中都有return语句时,执行代码的顺序是怎么样的,是根据哪个值来进行返回呢?
我们知道在处理异常时,finally中的代码是必定要执行的。这是由Java编译器决定的,在编译的时候将try模块的代码与finally模块的代码合并在一起,将catch模块的代码与finally模块的代码合并在一起,这是毫无疑问的。
这样,当finally模块有return那么将会执行finally中的return返回函数的结果,无论try、catch,还是函数体有没有return语句。所以该位置的return的优先级是最高的。
那么当finally没有return时是如何返回的呢?
这时在执行完try中的模块后,有return语句,实际不会真正的return,即只是会计算return中的表达式,之后将计算的结果保存在一个临时栈中,接着执行finally中的语句,最后才会从临时栈中取出之前的结果返回。
所以,函数的返回值是1而非30。
总体来说,return语句的位置有如下几种。
public static int getNumer() { try { return a; } catch (Exception e) { return b; } finally { return c; } return d; }
当无异常抛出时,返回的优先级如下:c>a>d
当然,如果c存在,d是不可达代码,编译会错误的,如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unreachable code
当有异常抛出时,返回的优先级如下:c>b>d
总之,大家记住,finally块中的return优先级最高,而函数体中的return的优先级最低就好了。