java中的try...catch...finally执行顺序
结论:
- 如果try中没有异常,则顺序为try→finally;如果try中有异常,顺序为try→catch→finally,并且异常之后的代码不会执行。
- 当try或catch中带有return时,会先执行return前的代码,然后暂时保存需要return的信息,[相当于将这里遇到的return的值存入到一个局部变量中。如果是基本数据类型,就是数据值,如果是引用类型,那就是地址值],再执行finally中的代码,最后再通过return返回之前保存的信息(前面提到的局部变量的值)。
- finally中有return时,会直接在finally中退出,导致try、catch中的return失效。
注意:
-
在第2点中,因为return保存的值是数据值,那么后面finally中除了再次遇到return,否则是不会影响到最终返回的值的。但是当return返回的是引用类型的话,虽然返回的值是不变的(地址值), 但引用的具体的东西中的内容是可以改变的。
-
对于第3点在finally中写return,编译是可以编译通过的,但是编译器会给予警告,所以不推荐在finally中写return,这会破坏程序的完整性
下面给出一个别人的测试的demo,包含了以上所有情况,基本上几个例子看完之后就弄明白了执行顺序了。
public class SeDemo {
/**
* 没有异常 try ,finally
* @return 3
*/
public static int divide(){
try {
return 1;
} catch (Exception e){
return 2;
} finally {
return 3;
}
}
/**
* 异常 try,catch,finally
* @return 3
*/
public static int divide1 (){
try {
int a = 1/0;
return 1;
} catch (Exception e){
return 2;
} finally {
return 3;
}
}
/**
* try ,finally
* @return 30
*/
public static int divide2 (){
int a;
try {
a = 10;
} catch (Exception e){
a = 20;
} finally {
a = 30;
}
return a;
}
/**
* try ,finally
* @return 10
*/
public static int divide3 (){
int a;
try {
a = 10;
return a;
} catch (Exception e){
a = 20;
} finally {
a = 30;
}
a++;
return a;
}
/**
* trh ,catch,finally
* @return 20
*/
public static int divide4 (){
int a;
try {
a = 10;
int b = 10 / 0;
} catch (Exception e){
a = 20;
return a;
} finally {
a = 30;
}
return a;
}
/**
* @return [1,3]
*/
public static List<Integer> divide5() {
List<Integer> list = new ArrayList<>();
try {
list.add(1);
} catch (Exception e) {
list.add(2);
} finally {
list.add(3);
}
return list;
}
/**
* @return [1,3]
*/
public static List<Integer> divide6() {
List<Integer> list = new ArrayList<>();
try {
list.add(1);
return list;
} catch (Exception e) {
list.add(2);
} finally {
list.add(3);
}
return list;
}
/**
* @return [1,2,3]
*/
public static List<Integer> divide7() {
List<Integer> list = new ArrayList<>();
try {
list.add(1);
int a = 1/0;
} catch (Exception e) {
list.add(2);
return list;
} finally {
list.add(3);
}
return list;
}
}

浙公网安备 33010602011771号