java中try,catch,finally中return,exit执行顺序

更新时间 🔔🕙 2024年9月22日

环境:JDK7

有时候会遇到在try的catch中有return语句,finally中也有return语句。
这时要小心执行顺序。

package test;

public class Test {

public static void main(String[] args) {
// catch与finally中都有return
String b = catch_finally_return();
System.out.println(b);
System.out.println();

// catch中都有return
b = catch_return();
System.out.println(b);
System.out.println();

// exit
exit();
}

// catch与finally中都有return,finally中的return会覆盖catch中的return
public static String catch_finally_return() {
try {
int a = 0;
int b = 2 / a;
} catch (Exception e) {
System.out.println("catch");
return "a";
} finally {
System.out.println("finally");
return "我是finally";
}
}

// catch命中后,只有catch中的return有效
public static String catch_return() {
try {
int a = 0;
int b = 2 / a;
} catch (Exception e) {
System.out.println("catch");
return "a";
} finally {
System.out.println("finally");
}
return "我是end";
}

// finally中的代码不会执行,System.exit的优先级最高
public static void exit() {
try {
int a = 0;
int b = 2 / a;
} catch (Exception e) {
System.out.println("catch");
System.exit(1);
} finally {
System.out.println("finally");
System.exit(2);
}
}

}

执行的结果是:

catch
finally
我是finally

catch
finally
a

catch
转载请备注引用地址:编程记忆 » java中try,catch,finally中return,exit执行顺序