文章目录
前言
在异常处理中try catch finally的执行顺序大家都知道是按顺序执行,如果try中代码没有异常,则进入finally中,如果try中有异常则执行catch 再执行finally,这里要探讨是特殊情况下try catch finally的执行情况
java中try cath finally的执行顺序
1、当try 或catch块中遇到return语句
- try中带有return语句的情况
/**
* try中带有return语句时
*/
public static int returnTest1(int a) {
try {
a++;
return a;
} catch (Exception e) {
System.out.println("catch 执行");
} finally {
System.out.println("finally 执行");
if (a==2){
return 0;
}
}
return 1;
}
- catch 中带有return语句的情况
/**
* catch中带有return 语句
*/
public static int returnTest2(int a) {
int b = 1;
try {
a++;
b = a / 0;
} catch (Exception e) {
b++;
System.out.println("catch 执行 b="+b);
return b;
} finally {
System.out.println("finally 执行");
if (b==2){
return 0;
}
}
return b;
}
分别调用两个方法得出结果:
finally 执行
0
catch 执行 b=2
finally 执行
0
由结果可知,无论是在try 或者catch 中带有return语句,在return之前都会调用finally中的语句方法才会返回结果。
这里注意看finally中的判断操作,显而易见的,当try 语句或者catch语句中 和 finally语句都存在return语句时,在方法返回前,finally语句的内容将被执行,并且finally语句的返回值将会覆盖原始的返回值。
2、当catch 或 finally抛出异常
- 当finally抛出异常
public static int returnTest3(int a) {
int b = 1;
try {
a++;
b = a / 0;
} catch (Exception e) {
b++;
System.out.println("catch 执行 b=" + b);
return b;
} finally {
if (b == 2) {
b = b / 0; //很明显这里或抛出异常,但是finally还是会执行
}
System.out.println("finally 执行");
}
return b;
}
打印结果是:
catch执行 b=2;
但是方法是没有返回值的,被异常中断
- 当catch 中抛出异常
public static int returnTest4(int a) {
int b = 1;
try {
a++;
b = a / 0;
} catch (Exception e) {
b++;
b =b/0;
System.out.println("catch 执行 b=" + b);
return b;
} finally {
System.out.println("finally 执行");
}
return b;
}
直接看打印结果:
finally 执行
这里finally还是执行了,可以感觉出finally块无论如何都会执行,但是真的是这样吗,下面举一个反例:
3、当在finally之前调用了System.exit(int)方法
public static int returnTest5(int a) {
int b = 1;
try {
a++;
b = a / 0;
} catch (Exception e) {
System.out.println("catch 执行");
System.exit(-1);
return b;
} finally {
System.out.println("finally 执行");
}
return b;
}
打印结果:
catch 执行
可以看出,当再finally之前调用System.exit(int)方法之后,finally是不会再执行的。当然该方法也没有返回值了。还有一种情况是直接断电或者关闭程序进程,当然这种情况不能直接演示,可以自己试试。、
总结:
- 当try 语句或者catch语句中 和 finally语句都存在return语句时,在方法返回前,finally语句的内容将被执行,并且finally语句的返回值将会覆盖原始的返回值。
- 当catch 块中抛出异常时,finally也照常执行,两者互不干扰;当然该方法是否存在返回值取决于finally中是否返回了。
- 正常情况下,无论如何finally块都会执行,前提是在之前没有调用System.exit(int)中断程序。