Java 把异常分为受检异常和非受检异常。文件读写应使用 try-with-resources 自动关闭流。
本节要点
- catch 捕获具体异常类型。
- finally 无论是否异常都会执行。
- try-with-resources 会自动调用 close。
代码示例
import java.io.*;
public class Demo {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("读取失败:" + e.getMessage());
}
}
}