Relations with Java finally try the return of

Java finally

Is how the implementation of
the Internet on this article many ways, this is mainly about some places try in return and finally a

try in the return
we all know, try there return is certainly to be returned, but if we try in return in finally in the return value of the operation result like that? So it seems a bit abstract, there is a code description is all about
[Java]

Plain Text View

Copy the code

?

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

 

We obviously let b + 50 in finally, the return of the last 150 b should not it? Why is it 100? Do not worry, I use another example to illustrate this is why

 

Finally Map Examples of
[Java]

Plain Text View

Copy the code

?

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


Why run result will be FINALLY?

In the above example we let in finally in the b + 50, but return back b or 100 ,. But this time we let map.put in finally in ( "KEY", "FINALLY" ), why was it changed the map? If we can change the map, then we are not finally make map = null yet? Finally, we are able to successfully System.out.println out?

FAQ doubt
this series of questions is very simple, in fact, this is a small cover-up about a return of

a.jpg

(31.26 KB, Downloads: 0)

 

 

a.jpg

b.jpg

(45.34 KB, Downloads: 0)

 

 

b.jpg


作者:傻大头
链接:https://juejin.im/post/5e8d749cf265da47e90d01ff
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发布了964 篇原创文章 · 获赞 11 · 访问量 3万+

Guess you like

Origin blog.csdn.net/xiaoyaGrace/article/details/105400486