finally释放资源

非Java资源,例如:打开文件、网络连接、数据库连接、数据库结果集,不能被工程回收,这里需要异常处理(例如关闭数据库连接)

代码格式

     try {
        //可能会生成异常语句
    } catch (Throwable e1) {
        //处理异常e1
    } catch (Throwable e2) {
        //处理异常e2
    } catch (Throwable e3) {
        //处理异常e3
    } finally { //最后异常处理都要走的步骤
        //释放资源
    }

代码示例

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Finally {
	public static void main(String[] args) {
		Date date = readDate();
		System.out.println("日期 = " + date);
	}

	private static Date readDate() {
		//IO文件输入流
		FileInputStream readfile = null;
		//IO文件输出流
		InputStreamReader ir = null;
		BufferedReader in= null;
		try {
			//通过FileInputStream读取一个文件文件
			readfile = new FileInputStream("readme.txt");
			ir = new InputStreamReader(readfile);
			in = new BufferedReader(ir);
			//读取文件中的一行数据
			String str = in.readLine();
			if(str == null){
				return null;
			}
			//初始化时间格式
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			//格式化时间格式
			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();
		}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;
	}
}
发布了94 篇原创文章 · 获赞 13 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_39559301/article/details/104751325