前言
在 Java 的异常处理中,try、catch 和 finally 是按顺序执行的。
如果 try 中没有异常,则顺序为 try→finally;
如果 try 中有异常,则顺序为 try→catch→finally。
但是,当 try、catch、finally 中都加入 return 之后,return 和 finally 的执行顺序是咋样的?
注:finally 代码块是一定会被执行的。
我总结为以下几条:
- 执行 try 代码块或 catch 代码块中的 return 语句之前,都会先执行 finally 语句;
- 无论在 finally 代码块中是否修改返回值,返回值都不会改变,仍然是执行 finally 代码块之前的值;
- finally 代码块中的 return 语句一定会执行,且是最终返回值。
测试
finally 代码块一定会在 try、catch 的return之前执行
public class Test1 {
// 结果:先执行 finally 语句块中的代码,再 执行 try 中的 return
public static int show() {
try {
return 1;
} finally {
System.out.println("执行finally模块");
}
}
public static void main(String[] args) {
System.out.println(show());
// 控制台打印:
// 执行finally模块
// 1
}
}
public class Test2 {
// 结果:当 try 代码块或者 catch 代码块中有 return 时,finally 中的代码总会在return之前执行
public static int show() {
try {
int a = 8 / 0;
return 1;
} catch (Exception e) {
return 2;
} finally {
System.out.println("执行finally模块");
}
}
public static void main(String[] args) {
System.out.println(show());
// 控制台打印:
// 执行finally模块
// 2
}
}
finally 代码块修改返回值,但是,不会改变 try 或者 catch 最后返回的内容
public class Test4 {
// 结果:在 finally 代码块中改变返回值并不会改变最后返回的内容。
public static int show() {
int result = 0;
try {
result = 1;
return result;
} finally {
System.out.println("执行finally模块");
result = 2;
}
}
public static void main(String[] args) {
System.out.println(show());
// 控制台打印:
// 执行finally模块
// 1
}
}
finally 代码块中的 return 语句 才是真正返回的结果
注:finally 代码块中最好不要包含 return 语句,否则程序会提前退出。
public class Test3 {
// 结果:当 finally 有返回值时,会直接返回该值,不会去返回 try 代码块或者 catch 代码块中的返回值。
public static int show() {
try {
int a = 8 / 0;
return 1;
} catch (Exception e) {
return 2;
} finally {
System.out.println("执行finally模块");
return 0;
}
}
public static void main(String[] args) {
System.out.println(show());
// 控制台打印:
// 执行finally模块
// 0
}
}