finally java return_Java中finally和return优先级

作为一名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;

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

packagecom.github.xuchengen.other;

/**

* 最终返回实例

* 作者:徐承恩

* 邮箱:xuchengen@gmail.com

* 日期:2019/11/4

*/

publicclassFinallyReturnExample{

publicstaticvoidmain(String[]args){

System.out.println(finallyReturn1());

System.out.println(finallyReturn2());

}

privatestaticStringfinallyReturn1(){

try{

thrownewRuntimeException();

}catch(Exceptione){

return"catch";

}finally{

return"finally";

}

}

privatestaticintfinallyReturn2(){

inta=1;

try{

returna;

}catch(Exceptione){

a=-1;

}finally{

a=30;

System.out.println(a);

}

returna;

}

}

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;

}

1

2

3

4

5

6

7

8

9

10

publicstaticintgetNumer(){

try{

returna;

}catch(Exceptione){

returnb;

}finally{

returnc;

}

returnd;

}

当无异常抛出时,返回的优先级如下:c>a>d

当然,如果c存在,d是不可达代码,编译会错误的,如下:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unreachable code

1

Exceptioninthread"main"java.lang.Error:Unresolvedcompilationproblem:Unreachablecode

当有异常抛出时,返回的优先级如下:c>b>d

总之,大家记住,finally块中的return优先级最高,而函数体中的return的优先级最低就好了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值