# trycatch
# try catch finally块中的finally语句是不是一定会被执行
至少有两种情况下finally语句是不会被执行的
- (1)try语句没有被执行到,如在try语句之前就返回了,这样finally语句就不会执行,这也说明了finally语句被执行的必要而非充分条件是:相应的try语句一定被执行到。
- (2)在try块中有System.exit(0);这样的语句,System.exit(0);是终止Java虚拟机JVM的,连JVM都停止了,所有都结束了,当然finally语句也不会被执行到。
# finally语句是在try的return之前执行还是之后执行
finally语句在return语句执行之后return返回之前执行的
/**
* 验证finally是在try的return之前还是之后运行
*/
@Test
public void testBack(){
System.out.println("testBackInt(88)结果:"+testBackInt(88));
}
private int testBackInt(int a){
try {
System.out.println("try语句快");
return a+=12;
} catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("finally语句块");
if (a>99){
System.out.println("a>99,a="+a);
}
}
return a;
}
// try语句快
// finally语句块
// a>99,a=100
// testBackInt(88)结果:100
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
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
return语句已经执行了再去执行finally语句,不过并没有直接返回,而是等finally语句执行完了再返回结果
# finally里也有return语句那么是不是就直接返回了
finally块中的return语句会覆盖try块中的return返回
@Test
public void testBack(){
System.out.println("testBackInt(88)结果:"+testBackInt(88));
}
private int testBackInt(int a){
try {
System.out.println("try语句快");
return a+=12;
} catch (Exception e){
System.out.println("catch语句块");
} finally {
System.out.println("finally语句块");
if (a>99){
System.out.println("a>99,a="+a);
}
return 200;
}
// return a;
}
// try语句快
// finally语句块
// a>99,a=100
// testBackInt(88)结果:200
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
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
说明finally里的return直接返回了,就不管try中还有返回语句
# 如果finally里没有return语句,但修改了b的值,那么try中return返回的是修改后的值还是原值
如果finally语句中没有return语句覆盖返回值,那么原来的返回值可能因为finally里的修改而
改变也可能不变
@Test
public void testBack(){
System.out.println("testBackInt(88)结果:"+testBackInt(88));
}
private int testBackInt(int a){
try {
System.out.println("try语句快");
return a+=12;
} catch (Exception e){
System.out.println("catch语句块");
} finally {
System.out.println("finally语句块");
if (a>99){
System.out.println("a>99,a="+a);
}
a=120;
}
return 3000;
}
// try语句快
// finally语句块
// a>99,a=100
// testBackInt(88)结果:100
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
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
@Test
public void testMapBack(){
System.out.println(testBackMap().get("key"));
}
private Map<String,String> testBackMap(){
Map<String,String> map = Maps.newHashMap();
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;
}
// finally
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
为什么上述代码中finally里
a = 120;并没有起到作用
map.put("key","finally");起了作用
map = null;却没起作用呢
Java到底是传值还是传址的问题了,简单来说就是:Java中只有传值没有传址,这也是为什么map = null这句不起作用
# 如果catch中有return语句呢?当然只有在异常的情况下才有可能会执行,那么是在finally之前就返回吗
当发生异常后,catch中的return执行情况与未发生异常时try中return的执行情况完全一样