zoukankan      html  css  js  c++  java
  • Finally语句块的运行

    一、finally语句块是否一定运行?

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

    (1)异常捕获机制finally块与try和catch块是关联的。既然是关联的假设try...catch...finally语句逻辑上达不到没有被运行,如在try语句之前就返回了,这样finally语句就不会运行,这也说明了finally语句被运行的必要而非充分条件是:对应的try...catch...finally语句一定被运行到。

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


    二、finally语句块是否一定会运行,遇到return怎么办?

    public class FinallyTest1 {
    	
    	public void  test(){
    		try{
    			System.out.println("Try statement block……");
    			return ;
    		}catch(Exception e){
    			System.out.println("Exception statement block……");
    		}finally{
    			System.out.println("在try语句块中return你再强大,也影响不了我finally语句块的继续运行,嘿嘿……");
    		}
    		
    	}
    	
    	public static void main(String[] args) {
    		FinallyTest1 t=new FinallyTest1();
    		t.test();
    	}
    }
    
    /*
     运行结果:
    	 Try statement block……
    	  在try语句块中return你再强大,也影响不了我finally语句块的继续运行,嘿嘿……
    	  
    总结:
    	 finally语句块的运行不会受到try语句块中的return的影响。

    */


    三、finally语句块不受return语句的影响。哪finally语句块究竟是在return之前还是之后运行?

    public class FinallyTest2 {
    	private int test(){	
    		int a=520;
    		try{
    			return a+=1314000;
    		}catch(Exception e){
    			System.out.println();
    		}finally{
    			System.out.println("Finally运行,a值为:"+a);
    			a=0;
    			System.out.println("小闹了一下(a=0),嘿嘿!

    "); } return 250; } public static void main(String[] args) { FinallyTest2 t=new FinallyTest2(); System.out.println("方法返回(return) :"+t.test()); } } /* 运行结果: Finally运行,a值为:1314520 小闹一下(a=0),嘿嘿。 方法返回(return) :1314520 总结: 在try语句块中运行到了return时,并非马上返回而是把return要返回的值计算出来先保存到内存中, 然后去运行finally语句块。然后再返回之前保存要return的值。

    */



    四、在返回之前运行在finally块中的语句,哪finally块中也return会怎么样呢?

    public class FinallyTest3 {
    	//@SuppressWarnings 批注同意您选择性地取消特定代码段(即,类或方法)中的警告。
    	@SuppressWarnings("finally")	
    	private int test(){	
    		try{
    			return 520;
    		}catch(Exception e){
    			System.out.println();
    		}finally{
    			return 5820;	//此处return语句会产生警告
    		}
    	}
    	
    	public static void main(String[] args) {
    		FinallyTest3 t=new FinallyTest3();
    		System.out.println("方法返回(return) :"+t.test());
    	}
    }
    /*
    执行结果:
     	方法返回(return) :5820
    	
    总结:
    	假设try和finally都有return 语句。则返回值以最后一个return语句的值作为返回,前面的一个被默认的牺牲啦。
    */



  • 相关阅读:
    什么是ORM
    ORM优缺点
    Azure 中快速搭建 FTPS 服务
    连接到 Azure 上的 SQL Server 虚拟机(经典部署)
    在 Azure 虚拟机中配置 Always On 可用性组(经典)
    SQL Server 2014 虚拟机的自动备份 (Resource Manager)
    Azure 虚拟机上的 SQL Server 常见问题
    排查在 Azure 中新建 Windows 虚拟机时遇到的经典部署问题
    上传通用化 VHD 并使用它在 Azure 中创建新 VM
    排查在 Azure 中新建 Windows VM 时遇到的部署问题
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/7219479.html
Copyright © 2011-2022 走看看