try/catch中finally的执行时间

时间:2022-08-19 05:15:27

前言
由于总是搞不清楚try/catch中的一个执行顺序,返回结果。所以总结一下

1.finally没有return 时,可以看出finally确实在return之前执行了
public static void main(String[] args) {
int aa = test1();
System.out.println(aa);
}

public static int test1(){
try{
System.out.println("try");
return 0;
}catch(Exception e){
System.out.println("catch");
return 1;
}finally {
System.out.println("finally");

}
}

//结果
//try
//finally
//0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2. finally有return 时,会覆盖其他语句中的return
public static void main(String[] args) {
int aa = test1();
System.out.println(aa);
}

public static int test1(){
try{
System.out.println("try");
return 0;
}catch(Exception e){
System.out.println("catch");
return 1;
}finally {
System.out.println("finally");
return 2;
}
}

//结果
//try
//finally
//2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
3.finally中对基本数据类型没有影响
public static int test1(){
int result = 6;
try{
System.out.println("try");
return result;
}catch(Exception e){
System.out.println("catch");
return 1;
}finally {
System.out.println("finally");
result = 3;
}
}

//结果try
//finally
//6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
4.finally中对引用型数据有影响
public static StringBuffer test1(){
StringBuffer str = new StringBuffer("I");
try{
System.out.println("try");
return str;
}catch(Exception e){
System.out.println("catch");
return null;
}finally {
System.out.println("finally");
str.append("am");
}
}

//结果try
//finally
// I am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
5.当try/catch外面有异常,finally不执行
public static int test2(){
int a = 5/0;
try{
System.out.println("try");
return a;
}catch(Exception e){
System.out.println("catch");
return 2;
}finally {
System.out.println("finally");
}
}
1
2
3
4
5
6
7
8
9
10
11
12

Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.jxl.face.Controller.EnumTest.test2(EnumTest.java:29)
at com.jxl.face.Controller.EnumTest.main(EnumTest.java:19)
1
2
3
4
6.异常在try/catch里面,finally无return
public static int test2(){

try{
int a = 5/0;
System.out.println("try");
return a;
}catch(Exception e){
System.out.println("catch");
return 2;
}finally {
System.out.println("finally");
}
}

//catch
//finally
//2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
7.异常在try/catch里面,finally有return
public static int test2(){

try{
int a = 5/0;
System.out.println("try");
return a;
}catch(Exception e){
System.out.println("catch");
return 2;
}finally {
System.out.println("finally");
return 3;
}
}

//catch
//finally
//3