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怎么用。

  • 相关阅读:
    【原创】【JNI】OPUS压缩与解压的JNI调用(.DLL版本)
    线性基学习笔记
    杜教筛&Min_25筛学习笔记
    LOJ2540 随机算法
    仙人掌&圆方树学习笔记
    CF487E Tourists
    BZOJ2125 最短路
    [SHOI2008]仙人掌图
    BZOJ4316 小C的独立集
    NOI2015 品酒大会
  • 原文地址:https://www.cnblogs.com/VersionP1/p/7498320.html
Copyright © 2011-2022 走看看