java中finally易错点

Demo01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Demo01 {
public static void main(String[] args) {
System.out.println(test());
}

public static int test(){
try{
return 1;
} catch (Exception e){

} finally{
System.out.println("I am finally");
}
return 0;
}
}

return语句是返回到调用函数处,跳出函数体,所有应当被执行的语句都应该在return语句之前被执行,因为finally语句是必须要被执行的,所以他被执行了。

Demo02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Demo02 {
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
try{
return 1;
} catch(Exception e){
return 2;
} finally {
return 3;
}
}
}

执行return 1之后,要执行finally,finally中已经有return 2了,已经跳出了函数体,就不会再回来了

Demo03

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Demo03 {
public static void main(String[] args) {
System.out.println(test());
}

public static int test(){
int test = 0;
try{
test = 1;
return test;
}catch (Exception e){
return 0;
} finally {
test = 3;
System.out.println("I am finally");
}
}
}

已经执行了test=3,为什么返回的不是3呢,因为在执行到try中的return语句的时候,会把return的值存到指定的位置,之后return 这个位置的值。仔细想想,合理。

Demo04

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Demo04 {
public static void main(String[] args) {
System.out.println(test());
}

public static StringBuffer test(){
StringBuffer sb = new StringBuffer("你好,赛格");
try{
return sb;
}catch (Exception e){
return null;
} finally {
sb.append(",学java"); //有效的
System.out.println("I am finally");
}
}
}

和Demo03不同的是,这个sb是引用类型,即使return sb的时候被保存,但保存的仅仅是引用(类似于地址),修改了引用处的值,返回过去。再使用引用,找寻引用处的值,修改自然是有效的。


java中finally易错点
https://blog.wangxk.cc/2020/09/12/java中finally易错点/
作者
Mike
发布于
2020年9月12日
许可协议