原文:https://blog.csdn.net/woshixuye/article/details/23546081
一、错误示例1
public void CopyFile ()
{
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("c:\\xy1.txt"); // 1.
fw = new FileWriter("c:\\xy2.txt"); // 2.
char[] charBuffer = new char[1024];
int len = 0;
while ((len = fr.read(charBuffer)) != -1) {
fw.write(charBuffer, 0, len);
}
System.out.println("文件复制成功");
} catch (IOException e) {
throw new RuntimeException("文件拷贝操作失败");
} finally {
try {
fr.close(); // 3.
fw.close(); // 4.
} catch (IOException e) {
throw new RuntimeException("关闭失败");
}
}
}
若1.中代码出错,fr根本就没有初始化,执行3.的时候就会报空指针异常。2.4.同样是这个道理。
二、错误示例2
public void CopyFile ()
{
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("c:\\xy1.txt"); // 1.
fw = new FileWriter("c:\\xy2.txt"); // 2.
char[] charBuffer = new char[1024];
int len = 0;
while ((len = fr.read(charBuffer)) != -1) {
fw.write(charBuffer, 0, len);
}
System.out.println("文件复制成功");
} catch (IOException e) {
throw new RuntimeException("文件拷贝操作失败");
} finally {
try {
if (null != fr) {
fr.close(); // 3.
}
if (null != fw) {
fw.close(); // 4.
}
} catch (IOException e) {
throw new RuntimeException("关闭失败"); // 5.
}
}
}
加上是否为空的判断可以避免空指针异常。但是如果3.执行出错,程序会直接进入5.而4.根本没有得到执行,导致无法关闭。
三、正确示例(伪)
public void CopyFile ()
{
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("c:\\xy1.txt");
fw = new FileWriter("c:\\xy2.txt");
char[] charBuffer = new char[1024];
int len = 0;
while ((len = fr.read(charBuffer)) != -1) {
fw.write(charBuffer, 0, len);
}
System.out.println("文件复制成功");
} catch (IOException e) {
throw new RuntimeException("文件拷贝操作失败"); //1.
} finally {
try {
if (null != fr) {
fr.close();
}
} catch (IOException e) {
throw new RuntimeException("关闭失败"); //2.
}
try {
if (null != fw) {
fw.close();
}
} catch (IOException e) {
throw new RuntimeException("关闭失败"); //3.
}
}
}
博主补充:
上面的代码处理流程是没问题的,但代码示例在1 2 3处有一些问题,在这里是不能使用throw的,如果使用throw将导致异常在被catch抓取后再次抛出,此时将会将异常抛到上层应用,导致程序中断,输入输出流无法关闭。示例作者的本意应该只是表明这里将会抓取到异常,但这样写的话容易给初学者造成误导,所以在这里补充说明一下。正确示例如下:
四、正确示例(真)
public void CopyFile ()
{
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("c:\\xy1.txt");
fw = new FileWriter("c:\\xy2.txt");
char[] charBuffer = new char[1024];
int len = 0;
while ((len = fr.read(charBuffer)) != -1) {
fw.write(charBuffer, 0, len);
}
System.out.println("文件复制成功");
} catch (IOException e) {
//此处可以打印错误日志
e.printStackTrace();
} finally {
try {
if (null != fr) {
fr.close();
}
} catch (IOException e) {
//此处可以打印错误日志
e.printStackTrace();
}
try {
if (null != fw) {
fw.close();
}
} catch (IOException e) {
//此处可以打印错误日志
e.printStackTrace();
}
}
}