Java finally 与try中return的关系

259 阅读2分钟

Java finally是怎么执行的
网上关于这样的文章很多,这里主要讲的是try里return与finally的一些地方

try里的return
众所周知,try里有return肯定是要返回的,但是如果我们在finally里对try里return的返回值操作了结果会是怎么样的呢?这样好像有点抽象,有一个代码说明是这么一回事

[Java]

纯文本查看__复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

//例子1

public class FinallyTest1 {

public static void main(String[] args) {

System.out.println(test3());

}

public static int test3() {

int b = 20`;`

try {

return b += 80`;`

} catch (Exception e) {

System.out.println(`"catch block"`);

} finally {

b += 50`;`

}

return 2000`;`

}

}

//return b==100

我们明明在finally里让b+50了,最后return的b不应该是150吗?为什么会是100呢?不要着急,我用另外的一个例子来说明这是为什么

Map的finally例子

[Java]

纯文本查看__复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

//例子2

public class FinallyTest2

{

public static void main(String[] args) {

System.out.println(getMap().get(`"KEY"`).toString());

}

public static Map<String, String> getMap() {

Map<String, String> map = new HashMap<String, String>();

map.put(`"KEY",` `"INIT");`

try {

map.put(`"KEY",` `"TRY");`

return map;

}

catch (Exception e) {

map.put(`"KEY",` `"CATCH");`

}

finally {

map.put(`"KEY",` `"FINALLY");`

map = null`;`

}

return map;

}

}

//System-->FINALLY

运行结果为什么会是FINALLY?

在上面一个例子中我们在finally中让b+50,但是return回来的b还是100,。可是这回我们在finally里让map.put(“KEY”, “FINALLY”),为什么却改变了map呢?如果我们能改变map的话,我们不是在finally让map=null了吗?最后我们却能成功System.out.println出来?

疑问解惑
这一连串的疑问其实非常简单,其实这是关于一个return的小障眼法

a.jpg

(31.26 KB, 下载次数: 0)

a.jpg

b.jpg

(45.34 KB, 下载次数: 0)

b.jpg