Java异常处理之释放资源

一、finally代码块

有时在try-catch语句中会占用一些非Java资源,如:打开文件、网络连接、打开数据库连接和使用数据 结果集等,这些资源并非Java资源,不能通过JVM的垃圾收集器回收,需要程序员释放。为了确保这 些资源能够被释放可以使用finally代码块或Java 7之后提供自动资源管理(Automatic Resource Management)技术。

try-catch语句后面还可以跟有一个finally代码块,try-catch-finally语句语法如下:

try{ 
//可能会生成异常语句
} catch(Throwable e1){ 
//处理异常e1
} catch(Throwable e2){ 
//处理异常e2
} catch(Throwable eN){ 
//处理异常eN
} finally{ 
//释放资源
}

无论try正常结束还是catch异常结束都会执行finally代码块
在这里插入图片描述
finally代码块流程图

使用finally代码如下:

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//finally代码块-资源释放
public class HelloWorld {
    public static void main(String[] args) {
        Date date = readDate();
        System.out.println("日期="+date);

    }
    public static Date readDate(){
        FileInputStream readfile = null;
        InputStreamReader ir = null;
        BufferedReader in = null;
        try {
//            调用FileInputStream()构造方法可能会发生FileNotFoundException异常
            readfile = new FileInputStream("readme.txt");
            ir = new InputStreamReader(readfile);

            in = new BufferedReader(ir);
//            读取文件中的一行数据, 调用BufferedReader输入流的readLine()方法可能会发生IOException异常
            String str = in.readLine();
            if (str == null){
                return null;
            }
//            调用SimpleDateFormat()方法可能会发生ParseException异常
            DateFormat df  = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date date = df.parse(str);
            return date;
//          应该先捕获FileNotFoundException异常后捕获IOException(先捕获子类异常)
        } catch (FileNotFoundException e) {
            System.out.println("处理FileNotFoundException");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("处理IOException");
            e.printStackTrace();
        } catch (ParseException e) {
            System.out.println("处理ParseException");
            e.printStackTrace();
        }finally {
//            释放资源
            try {
//                通过关闭流释放资源
                if(readfile != null){
                    readfile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try{
//                通过关闭流释放资源
                if (ir !=null){
                    ir.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try{
//                通过关闭流释放资源
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }return null;
    }
}

二、自动资源管理

在Java 7之后提供自动资源管理(Automatic Resource Management)技术,可以替代finally 代码块,优化代码结构,提高程序可读性。
自动资源管理是在try语句上的扩展,语法如下:

try (声明或初始化资源语句) { 
//可能会生成异常语句
} catch(Throwable e1){
//处理异常e1
} catch(Throwable e2){
//处理异常e1
} catch(Throwable eN){
//处理异常eN }

代码如下:

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//自动资源管理
public class HelloWorld1 {
    public static void main(String[] args) {
        Date date = readDate();
        System.out.println(date);
    }
    public static Date readDate(){
//        自动资源管理
//        调用FileInputStream()构造方法可能会发生FileNotFoundException异常,
        try (FileInputStream readfile = new FileInputStream("raedme.txt");
             InputStreamReader ir = new InputStreamReader(readfile);
             BufferedReader in  = new BufferedReader(ir)){

//            读取文件中的一行数据, 调用BufferedReader输入流的readLine()方法可能会发生IOException异常
            String str = in.readLine();
            if(str == null){
                return null;
            }
//            调用SimpleDateFormat()方法可能会发生ParseException异常
            DateFormat df  = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date date = df.parse(str);
            return date;

        } catch (FileNotFoundException e) {
            System.out.println("处理FileNotFoundException");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("处理IOException");
            e.printStackTrace();
        } catch (ParseException e) {
            System.out.println("处理ParseException");
            e.printStackTrace();
        }
        return null;
    }
}

采用了自动资源管理后不再需要finally代码块,不需 要自己close这些资源,释放过程交给了JVM。
以上内容仅供参考学习,如有侵权请联系我删除!

发布了69 篇原创文章 · 获赞 7 · 访问量 3339

猜你喜欢

转载自blog.csdn.net/weixin_45366499/article/details/104249162
今日推荐