finally块详解

来源:互联网 发布:linux vm commit over 编辑:程序博客网 时间:2024/06/10 04:10
/*异常体系:--------| Throwable  所有错误或者异常的父类--------------| Error(错误)--------------| Exception(异常) 异常一般都通过代码处理 ------------------| 运行时异常: 如果一个方法内部抛出了一个运行时异常,那么方法上 可以声明也可以不 声明,调用者可以以处理也可以不处理。------------------| 编译时异常(非运行时异常、受检异常):  如果一个方法内部抛出了一个编译时异常对象,那么方法上就必须要声明,而且调用者也必须要处理。运行时异常: RuntimeException以及RuntimeException子类 都是属于运行时异常。编译时异常: 除了运行时异常就是编译异常。疑问: 为什么java编译器会如此严格要求编译时异常,对运行时异常如此宽松?    运行时异常都是可以通过程序员良好的编程习惯去避免,所以java编译器就没有严格要求处理运行时异常。*/import java.security.acl.*;class Demo4 {    public static void main(String[] args) throws InterruptedException    {            int[] arr = null;            div(4,0,arr);         Object o = new Object();         o.wait();    }    public static void div(int a , int b ,int[] arr) {        if(b==0){            return;        }        int c = a/b;        System.out.println("c = "+c);        if(arr!=null){            System.out.println("数组的长度: "+arr.length);        }    }}
/*finally 块;finally块的 使用前提是必须要存在try块才能使用。finally块的代码在任何情况下都会执行的,除了jvm退出的情况。finally非常适合做资源释放的工作,这样子可以保证资源文件在任何情况下都 会被释放。try块的三种组合方式:第一种: 比较适用于有异常要处理,但是没有资源要释放的。         try{            可能发生异常的代码            }catch(捕获的异常类型 变量名){                处理异常的代码            }第二种:比较适用于既有异常要处理又要释放资源的代码。        try{            可能发生异常的代码            }catch(捕获的异常类型 变量名){                处理异常的代码            }finally{                 释放资源的代码;            }第三种: 比较适用于内部抛出的是运行时异常,并且有资源要被释放。           try{            可能发生异常的代码            }finally{                 释放资源的代码;            }*/class Demo5 {    public static void main(String[] args)     {        //System.out.println("Hello World!");        div(4,0);    }    public static void div(int a, int b){        try{            if(b==0){                System.exit(0);//退出jvm            }            int c = a/b;            System.out.println("c="+ c);        }catch(Exception e){            System.out.println("出了除数为0的异常...");            throw e;        }finally{            System.out.println("finall块的代码执行了..");        }    }}
/*fianlly释放资源的代码*/import java.io.*;class Demo6 {    public static void main(String[] args)     {        FileReader fileReader = null;        try{            //找到目标文件            File file = new File("f:\\a.txt");            //建立程序与文件的数据通道            fileReader = new FileReader(file);            //读取文件            char[] buf = new char[1024];            int length = 0;             length = fileReader.read(buf);            System.out.println("读取到的内容:"+ new     String(buf,0,length));        }catch(IOException e){            System.out.println("读取资源文件失败....");        }finally{            try{                //关闭资源                fileReader.close();                System.out.println("释放资源文件成功....");            }catch(IOException e){                System.out.println("释放资源文件失败....");            }        }    }}
0 0
原创粉丝点击