先捕获FileNotFoundException再捕获IOException,优先使用try-with-resources管理资源;文件未找到通常因路径错误,其他IO异常统一处理,确保资源自动关闭且异常精准捕获。

在Java中处理IOException和FileNotFoundException,关键在于理解它们的继承关系并合理使用异常捕获机制。这两个异常都属于检查型异常(checked exception),必须显式处理才能通过编译。
理解异常的继承关系
FileNotFoundException是IOException的子类。这意味着:
- 捕获
IOException时会同时捕获其所有子类,包括FileNotFoundException - 如果要分别处理,应先捕获
FileNotFoundException,再捕获IOException
- 否则,父类异常会“屏蔽”子类异常,导致无法单独处理
使用try-catch块进行异常捕获
当读写文件可能出错时,应将代码放在try块中,并针对不同异常提供处理逻辑:
import java.io.*;
public class FileHandler {
public void readFile(String filePath) {
FileInputStream fis = null;
try {
fis = new FileInputStream(filePath);
int data = fis.read();
while (data != -1) {
System.out.print((char) data);
data = fis.read();
}
} catch (FileNotFoundException e) {
System.err.println("文件未找到:" + e.getMessage());
} catch (IOException e) {
System.err.println("读取文件时发生IO错误:" + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.err.println("关闭流时出错:" + e.getMessage());
}
}
}
}
}
使用try-with-resources简化资源管理
Java 7引入了try-with-resources语句,能自动关闭实现了AutoCloseable的资源,避免手动关闭出错:
立即学习“Java免费学习笔记(深入)”;
eoeAndroid特刊第二期:Android图像处理篇 pdf,eoeAndroid策划的第二篇专题,主要整理和翻译在Android中进行图像处理的一些资源和文章,通过本专题内容的学习,您可以掌握如何在Android上对图片编程,主要包括但不限于如下方向的内容: • Android中支持的图片格式介绍; • Android中图片库介绍 • 图片的显示(本地的,网络的); • 图片的格式转换; •
public void readFileWithResources(String filePath) {
try (FileInputStream fis = new FileInputStream(filePath)) {
int data = fis.read();
while (data != -1) {
System.out.print((char) data);
data = fis.read();
}
} catch (FileNotFoundException e) {
System.err.println("文件不存在:" + filePath);
} catch (IOException e) {
System.err.println("读取失败:" + e.getMessage());
}
}
这种方式更简洁,且能确保流被正确关闭,即使发生异常也不会泄漏资源。
抛出异常让调用者处理
如果你的方法不打算自己处理异常,可以将其声明抛出,由上层调用者决定如何应对:
public void readFileAndThrow(String filePath) throws IOException {
try (FileInputStream fis = new FileInputStream(filePath)) {
// 处理文件
}
}
这样调用该方法的代码就必须用try-catch包裹或继续向上抛出。
基本上就这些。关键是根据实际场景选择捕获还是抛出,并优先使用try-with-resources管理资源,避免遗漏关闭操作。处理文件相关操作时,FileNotFoundException通常表示路径问题,而其他IO问题则归为IOException,区分对待有助于定位问题根源。









