zoukankan      html  css  js  c++  java
  • Java:有关try、catch和finally的学习(供自己参考)

    Java:有关try、catch和finally的学习

    在看到书本的时候对finally的介绍是:不论是否在try块中产生异常,都会执行finally。当时对这句话的理解不够深,误以为在try...catch的结构中finally会必定执行。当时我产生一个疑问:catch已经对异常进行处理了,那后面的语句势必会执行,无论是否有finally。为此我还做了个小程序来验证。

    ExceptionDemo.java

    Version 1:

    /**
     * Created by Funny_One on 2017/8/30.
     */
    public class ExceptionDemo {
        public static void main(String[] args){
            try{
                int b = 1/0;
            }catch (Exception e){
                System.out.println("This is an Exception");
            }
            System.out.println("Not finally yet");
        }
    }
    
    

    Version 2:

    /**
     * Created by Funny_One on 2017/8/30.
     */
    public class ExceptionDemo {
        public static void main(String[] args){
            try{
                int b = 1/0;
            }catch (Exception e){
                System.out.println("This is an Exception");
            }
            finally {
                System.out.println("Not finally yet");
            }
    
        }
    }
    
    

    结果:

    这就很纳闷了。。。。然后和同学讨论,我们注意到书上有这么两句话:“不论是正常退出try块,还是因为抛出一个异常而退出,都要执行finally。”以及“try后面不一定要加catch”于是我们想到会不会不要catch块的时候才能展示出finally的功能???于是我们改变程序的代码。

    Version 3:

    public class ExceptionDemo {
        public static void main(String[] args){
            try{
                int b = 1/0;
            }
                
          
                System.out.println("Not finally yet");
            
    
        }
    }
    
    

    但这个版本连编译都无法通过,运行后出现了错误:

    根据错误的要求,我在代码中加上了finally:

    Version 4 :

    /**
     * Created by Funny_One on 2017/8/30.
     */
    public class ExceptionDemo {
        public static void main(String[] args){
            try{
                int b = 1/0;
            }
                
            finally {
                System.out.println("Not finally yet");
            }
    
        }
    }
    
    

    结果:

    此外,还有一个要,程序先执行了finally中的语句,然后才开始报出异常。至此,知道了finally怎么用。

  • 相关阅读:
    如果使用EntityFramework6链接Mysql
    MongoDB联合查询 -摘自网络
    “TableDetails”中列“IsPrimaryKey”的值为DBNull. Mysql EntityFramework
    使用NPOI 转换Excel TO HTML (导出格式不如原生Excel好看)
    如何使用ODBC搭配dsn链接数据库
    Ubuntu16.04安装配置sublime text3
    ubuntu16.04编译安装php7.2
    ubuntu16.04安装flash player与谷歌浏览器(chrome)
    ubuntu16编译安装mysql5.7
    phpstorm+wamp+xdebug配置php调试环境
  • 原文地址:https://www.cnblogs.com/VersionP1/p/7498320.html
Copyright © 2011-2022 走看看