最后总结:finally块的语句在try或catch中的return语句执行之后返回之前执行且finally里的修改语句不能影响try或catch中return已经确定的返回值,若finally里也有return语句则覆盖try或catch中的return语句直接返回。
如果finally语句中没有return语句覆盖返回值,那么原来的返回值就不会因为finally里的修改而改变。
- public class FinallyTest3 {
- public static void main(String[] args) {
- System.out.println(test3());
- }
- public static int test3() {
- int b = 20;
- try {
- System.out.println("try block");
- return b += 80;
- } catch (Exception e) {
- System.out.println("catch block");
- } finally {
- System.out.println("finally block");
- if (b > 25) {
- System.out.println("b>25, b = " + b);
- }
- b = 150;
- }
- return 2000;
- }
- }
try块里的return语句在异常的情况下不会被执行,这样具体返回哪个看情况。
- public class FinallyTest4 {
- public static void main(String[] args) {
- System.out.println(test4());
- }
- public static int test4() {
- int b = 20;
- try {
- System.out.println("try block");
- b = b / 0;
- return b += 80;
- } catch (Exception e) {
- b += 15;
- System.out.println("catch block");
- } finally {
- System.out.println("finally block");
- if (b > 25) {
- System.out.println("b>25, b = " + b);
- }
- b += 50;
- }
- return 204;
- }
- }