try-catch-finally执行顺序

异常处理方式之一:try-catch-finally

格式

try{
//可能出现异常的代码
}catch(异常类型1 变量名){
//处理异常的方式1
}catch(异常类型2 变量名){
//处理异常的方式2
}catch(异常类型3 变量名3){
//处理异常的方式3
}
...
finally{
//一定会执行的代码
}

说明:

  1. try代码块中有异常时,会根据异常类型进入相应的catch。
  1. finally可选,如果有finally,那finally中的代码一定会执行。

问题:如果try、catch和finally中都有返回值,会返回什么结果呢?

test1:没有异常

public class Try_catch_Test {
public static void main(String[] args) {
String res = test();
System.out.println(res);
}
public static String test(){
try{
System.out.println("我在try里");
return "返回:try";
}catch (Exception e){
System.out.println("我在catch里");
return "返回:catch";
}finally {
System.out.println("我在finally里");
}
}
}

测试的结果:

分析:没有异常所以没有执行catch中的代码,执行顺序是try=>finally=>return;

test2:发生异常

public class Try_catch_Test {
public static void main(String[] args) {
String res = test();
System.out.println(res);
}
public static String test(){
try{
System.out.println("我在try里");
int i = 5 / 0;
return "返回:try";
}catch (Exception e){
System.out.println("我在catch里");
return "返回:catch";
}finally {
System.out.println("我在finally里");
}
}
}

测试的结果:

分析:在try中发生异常时,没有正常返回,会在catch中捕获异常。执行顺序是try=>catch=>finally=>return;

test3:finally中有返回

上面已经分析了不发生异常时不进入catch,finally的语句又一定会执行。

public class Try_catch_Test {
public static void main(String[] args) {
String res = test();
System.out.println(res);
}
public static String test(){
try{
System.out.println("我在try里");
return "返回:try";
}catch (Exception e){
System.out.println("我在catch里");
return "返回:catch";
}finally {
System.out.println("我在finally里");
return "返回:finally";
}
}
}

测试的结果为:


如果发生异常,进入catch,但最终返回的仍是finally语句的结果。

public class Try_catch_Test {
public static void main(String[] args) {
String res = test();
System.out.println(res);
}
public static String test(){
try{
System.out.println("我在try里");
int i = 5 / 0;
return "返回:try";
}catch (Exception e){
System.out.println("我在catch里");
return "返回:catch";
}finally {
System.out.println("我在finally里");
return "返回:finally";
}
}
}

测试的结果为:

结论

  1. try中没有异常时不会执行catch,出现异常时执行顺序为try-catch-finally
  1. finally中有return语句时,会忽略try、catch中的返回语句,只返回finally的结果。
------ 本文结束感谢您的阅读 ------