黑马程序员技术交流社区
标题:
IO异常的处理方式
[打印本页]
作者:
l6781155
时间:
2015-7-9 09:28
标题:
IO异常的处理方式
一定要关闭资源,所以close方法放在finally中
close方法也会抛出异常,所以close要单独try catch一次,
并且要判断当对象创建成功时才能调用close,否则将会抛出异常
如果有多个文件需要关闭,要分别判断每一个是否为空
package com.mytest;
import java.io.FileWriter;
import java.io.IOException;
public class test02 {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter("Demo.txt");
fw.write("hello IO");
} catch (IOException e) {
System.out.println(e.toString());
} finally {
try {
// 如果文件没创建成功,fw调用close方法将会出现异常
if (fw != null) {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
复制代码
作者:
dajiaoya
时间:
2015-7-9 10:04
分享快乐,赞一个
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2