Java finally语句到底是在return之前还是之后执行?

网上有很多人探讨Java中异常捕获机制try...catch...finally块中的finally语句是不是一定会被执行?很多人都说不是,当然他们的回答是正确的,经过我试验,至少有两种情况下finally语句是不会被执行的:

(1)try语句没有被执行到,如在try语句之前就返回了,这样finally语句就不会执行,这也说明了finally语句被执行的必要而非充分条件是:相应的try语句一定被执行到。

(2)在try块中有System.exit(0);这样的语句,System.exit(0);是终止Java虚拟机JVM的,连JVM都停止了,所有都结束了,当然finally语句也不会被执行到。


当然还有很多人探讨Finally语句的执行与return的关系,颇为让人迷惑,不知道finally语句是在try的return之前执行还是之后执行?我也是一头雾水,我觉得他们的说法都不正确,我觉得应该是:finally语句是在try的return语句执行之后,return返回之前执行。这样的说法有点矛盾,也许是我表述不太清楚,下面我给出自己试验的一些结果和示例进行佐证,有什么问题欢迎大家提出来。


1. finally语句在return语句执行之后return返回之前执行的。

  1. public class FinallyTest1 { 
  2.  
  3.     public staticvoid main(String[] args) { 
  4.          
  5.         System.out.println(test1()); 
  6.     } 
  7.  
  8.     public staticint test1() { 
  9.         int b = 20
  10.  
  11.         try
  12.             System.out.println("try block"); 
  13.  
  14.             return b += 80;  
  15.         } 
  16.         catch (Exception e) { 
  17.  
  18.             System.out.println("catch block"); 
  19.         } 
  20.         finally
  21.              
  22.             System.out.println("finally block"); 
  23.              
  24.             if (b > 25) { 
  25.                 System.out.println("b>25, b = " + b); 
  26.             } 
  27.         } 
  28.          
  29.         return b; 
  30.     } 
  31.      
public class FinallyTest1 {

	public static void main(String[] args) {
		
		System.out.println(test1());
	}

	public static int test1() {
		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);
			}
		}
		
		return b;
	}
	
}

运行结果是:

  1. try block 
  2. finally block 
  3. b>25, b = 100 
  4. 100 
try block
finally block
b>25, b = 100
100
说明return语句已经执行了再去执行finally语句,不过并没有直接返回,而是等finally语句执行完了再返回结果。

如果觉得这个例子还不足以说明这个情况的话,下面再加个例子加强证明结论:

  1. public class FinallyTest1 { 
  2.  
  3.     public staticvoid main(String[] args) { 
  4.          
  5.         System.out.println(test11()); 
  6.     } 
  7.      
  8.     public static String test11() { 
  9.         try
  10.             System.out.println("try block"); 
  11.  
  12.            return test12(); 
  13.       } finally
  14.            System.out.println("finally block"); 
  15.        } 
  16.   } 
  17.  
  18.   public static String test12() { 
  19.        System.out.println("return statement"); 
  20.  
  21.        return "after return"
  22.    } 
  23.      
public class FinallyTest1 {

	public static void main(String[] args) {
		
		System.out.println(test11());
	}
	
	public static String test11() {
        try {
            System.out.println("try block");

           return test12();
      } finally {
           System.out.println("finally block");
       }
  }

  public static String test12() {
       System.out.println("return statement");

       return "after return";
   }
	
}
运行结果为:

  1. try block 
  2. return statement 
  3. finally block 
  4. after return 
try block
return statement
finally block
after return

说明try中的return语句先执行了但并没有立即返回,等到finally执行结束后再

这里大家可能会想:如果finally里也有return语句,那么是不是就直接返回了,try中的return就不能返回了?看下面。


2. finally块中的return语句会覆盖try块中的return返回。

  1. public class FinallyTest2 { 
  2.  
  3.     public staticvoid main(String[] args) { 
  4.  
  5.         System.out.println(test2()); 
  6.     } 
  7.  
  8.     public staticint test2() { 
  9.         int b = 20
  10.  
  11.         try
  12.             System.out.println("try block"); 
  13.  
  14.             return b += 80
  15.         } catch (Exception e) { 
  16.  
  17.             System.out.println("catch block"); 
  18.         } finally
  19.  
  20.             System.out.println("finally block"); 
  21.  
  22.             if (b > 25) { 
  23.                 System.out.println("b>25, b = " + b); 
  24.             } 
  25.  
  26.             return 200
  27.         } 
  28.  
  29.         // return b; 
  30.     } 
  31.  
public class FinallyTest2 {

    public static void main(String[] args) {

        System.out.println(test2());
    }

    public static int test2() {
        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);
            }

            return 200;
        }

        // return b;
    }

}

运行结果是:

  1. try block 
  2. finally block 
  3. b>25, b = 100 
  4. 200 
try block
finally block
b>25, b = 100
200

这说明finally里的return直接返回了,就不管try中是否还有返回语句,这里还有个小细节需要注意,finally里加上return过后,finally外面的return b就变成不可到达语句了,也就是永远不能被执行到,所以需要注释掉否则编译器报错。

这里大家可能又想:如果finally里没有return语句,但修改了b的值,那么try中return返回的是修改后的值还是原值?看下面。


3. 如果finally语句中没有return语句覆盖返回值,那么原来的返回值就不会因为finally里的修改而改变。

  1. public class FinallyTest3 { 
  2.  
  3.     public staticvoid main(String[] args) { 
  4.  
  5.         System.out.println(test3()); 
  6.     } 
  7.  
  8.     public staticint test3() { 
  9.         int b = 20
  10.  
  11.         try
  12.             System.out.println("try block"); 
  13.  
  14.             return b += 80
  15.         } catch (Exception e) { 
  16.  
  17.             System.out.println("catch block"); 
  18.         } finally
  19.  
  20.             System.out.println("finally block"); 
  21.  
  22.             if (b > 25) { 
  23.                 System.out.println("b>25, b = " + b); 
  24.             } 
  25.  
  26.             b = 150
  27.         } 
  28.  
  29.         return 2000
  30.     } 
  31.  
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;
    }

}

运行结果是:

  1. try block 
  2. finally block 
  3. b>25, b = 100 
  4. 100 
try block
finally block
b>25, b = 100
100
finally里的b = 150;并没有起到作用,这貌似是前面说的有些矛盾,因为前面说try中的return是在finally执行完了才返回的,这里我的解释是:因为try中的return语句已经执行完了只是还没有返回,但是它的返回值已经确定下来了(这里是100),已经跟b这个变量无关了,不会再根据b的值决定返回什么,所以finally里对b的修改只影响b的值对原来已脱离b影响的返回值没有一点影响。这同时也说明了返回语句是try中的return语句而不是finally外面的return b;这句,不相信的话可以试下,将return b;改为return 294,对原来的结果没有一点影响。

这里大家可能又要想:是不是每次返回的一定是try中的return语句呢?那么finally外的return b不是一点作用没吗?请看下面。


4. try块里的return语句在异常的情况下不会被执行,这样具体返回哪个看情况。

  1. public class FinallyTest4 { 
  2.  
  3.     public staticvoid main(String[] args) { 
  4.  
  5.         System.out.println(test4()); 
  6.     } 
  7.  
  8.     public staticint test4() { 
  9.         int b = 20
  10.  
  11.         try
  12.             System.out.println("try block"); 
  13.  
  14.             b = b / 0
  15.  
  16.             return b += 80
  17.         } catch (Exception e) { 
  18.  
  19.             b += 15
  20.             System.out.println("catch block"); 
  21.         } finally
  22.  
  23.             System.out.println("finally block"); 
  24.  
  25.             if (b > 25) { 
  26.                 System.out.println("b>25, b = " + b); 
  27.             } 
  28.  
  29.             b += 50
  30.         } 
  31.  
  32.         return 204
  33.     } 
  34.  
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;
    }

}
运行结果是:

  1. try block 
  2. catch block 
  3. finally block 
  4. b>25, b = 35 
  5. 85 
try block
catch block
finally block
b>25, b = 35
85

这里因为在return之前发生了除0异常,所以try中的return不会被执行到,而是接着执行捕获异常的catch语句和最终的finally语句,此时两者对b的修改都影响了最终的返回值,这时return b;就起到作用了。当然如果你这里将return b改为return 300什么的,最后返回的就是300,这毋庸置疑。

这里大家可能又有疑问:如果catch中有return语句呢?当然只有在异常的情况下才有可能会执行,那么是在finally之前就返回吗?看下面。


5. 当发生异常后,catch中的return执行情况与未发生异常时try中return的执行情况完全一样。

  1. public class FinallyTest5 { 
  2.  
  3.     public staticvoid main(String[] args) { 
  4.  
  5.         System.out.println(test5()); 
  6.     } 
  7.  
  8.     public staticint test5() { 
  9.         int b = 20
  10.  
  11.         try
  12.             System.out.println("try block"); 
  13.              
  14.             b = b /0
  15.  
  16.             return b += 80
  17.         } catch (Exception e) { 
  18.  
  19.             System.out.println("catch block"); 
  20.             return b += 15
  21.         } finally
  22.  
  23.             System.out.println("finally block"); 
  24.  
  25.             if (b > 25) { 
  26.                 System.out.println("b>25, b = " + b); 
  27.             } 
  28.  
  29.             b += 50
  30.         } 
  31.  
  32.         //return b; 
  33.     } 
  34.  
public class FinallyTest5 {

	public static void main(String[] args) {

		System.out.println(test5());
	}

	public static int test5() {
		int b = 20;

		try {
			System.out.println("try block");
			
			b = b /0;

			return b += 80;
		} catch (Exception e) {

			System.out.println("catch block");
			return b += 15;
		} finally {

			System.out.println("finally block");

			if (b > 25) {
				System.out.println("b>25, b = " + b);
			}

			b += 50;
		}

		//return b;
	}

}

运行结果如下:

  1. try block 
  2. catch block 
  3. finally block 
  4. b>25, b = 35 
  5. 35 
try block
catch block
finally block
b>25, b = 35
35

说明了发生异常后,catch中的return语句先执行,确定了返回值后再去执行finally块,执行完了catch再返回,finally里对b的改变对返回值无影响,原因同前面一样,也就是说情况与try中的return语句执行完全一样。


最后总结:finally块的语句在try或catch中的return语句执行之后返回之前执行且finally里的修改语句不能影响try或catch中return已经确定的返回值,若finally里也有return语句则覆盖try或catch中的return语句直接返回。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值