一、程序无异常
public class TestCatch {
public int getCatch(String number) {
try {
Integer.parseInt(number);
} catch (Exception e) {
System.out.println("catch block");
return 1;
} finally {
System.out.println("final block");
return 2;
}
// return 3;
}
public static void main(String[] args) {
TestCatch testCatch = new TestCatch();
System.out.println(testCatch.getCatch("2"));
}
}
执行结果:
final block
2
二、程序有异常
1、finally无返回值
finally无返回值,那必定try中有返回值,或者执行完try流程之后,最后写返回值。
public class TestCatch {
public int getCatch(String number) {
try {
Integer.parseInt(number);
return 3;
} catch (Exception e) {
System.out.println("catch block");
return 1;
} finally {
System.out.println("final block");
}
//返回值写try里或者写在try流程外
// return 3;
}
public static void main(String[] args) {
TestCatch testCatch = new TestCatch();
System.out.println(testCatch.getCatch(null));
}
}
执行结果:
说明:遇到异常先走catch,所以输出了catch block,然后走了return 1.但是最终又走了finally,发现无返回值,所以又重新走return 1 将结果返回。
catch block
final block
1
2、finally有返回值
public class TestCatch {
public int getCatch(String number) {
try {
Integer.parseInt(number);
return 3;
} catch (Exception e) {
System.out.println("catch block");
return 1;
} finally {
System.out.println("final block");
return 3;
}
}
public static void main(String[] args) {
TestCatch testCatch = new TestCatch();
System.out.println(testCatch.getCatch(null));
}
}
执行结果:
说明:最终走finally有返回值,直接返回
catch block
final block
3
三:总结
代码顺序执行从try到finally,由于finally是无论如何都会执行的,所以try里的语句并不会直接返回。理解起来就是一个局部变量指向的问题,本代码测试并未使用变量,其实一个意思。
- finally语句总会执行
- 尽量不要在finally中使用return语句,如果使用的话,会忽略try、catch中的返回语句,也会忽略try、catch中的异常,屏蔽了错误的发生
- finally中避免再次抛出异常,一旦finally中发生异常,代码执行将会抛出finally中的异常信息,try、catch中的异常将被忽.也就失去了try语法的效果。