IO异常的处理
1. JDK7前处理
我们知道Java中异常处理有两种方式,一种是throw,一种是try-catch,我们首先要知道这两种方式的使用场景。
throw 异常之后,后面的代码将不会执行
try-catch时,即使catch到了异常之后,后面的代码还是会继续执行
刚学习的时候为了方便我们经常使用throw将异常抛出,而实际开发中并不能这样处理,建议使用 try…catch…finally 代码块,处理异常部分。
public class HandleException {
public static void main(String[] args) {
// 字符输出流 声明变量
FileWriter fw = null;
try {
//创建流对象
fw = new FileWriter("fw.txt");
// 写出数据
fw.write("justweb程序员"); //justweb程序员
} catch (IOException e) {
e.printStackTrace();
} finally {
// 在finally中关闭资源
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2. JDK7的处理
还可以使用JDK7优化后的 try-with-resource 语句,该语句确保了每个资源在语句结束时关闭。所谓的资源(resource)是指在程序完成后,必须关闭的对象。
public class HandleException {
public static void main(String[] args) {
// 创建流对象
try ( FileWriter fw = new FileWriter("fw.txt"); ) {
// 写出数据
fw.write("简维程序员"); //简维程序员
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. JDK9的改进(了解内容)
JDK9中 try-with-resource 的改进,对于 引入对象 的方式,支持的更加简洁。
被引入的对象,同样可以自动关闭,无需手动close,我们来了解一下格式。
public class TryDemo {
public static void main(String[] args) throws IOException {
// 创建流对象
final FileReader fr = new FileReader("in.txt");
FileWriter fw = new FileWriter("out.txt");
// 引入到try中
try (fr; fw) {
// 定义变量
int b;
// 读取数据
while ((b = fr.read())!=‐1) {
// 写出数据
fw.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}