如何在Java中优雅地处理IO操作异常
在Java中,我们通常使用try-catch-finally语句来优雅地处理IO操作异常。以下是一个例子:
import java.io.*;
public class IOExceptionHandling {
public static void main(String[] args) {
try (FileReader fr = new FileReader("non_existent_file.txt")) {
// 执行读取操作
String content = fr.read();
System.out.println(content);
} catch (FileNotFoundException e) {
// 处理文件不存在的异常
System.err.println("File not found: " + e.getMessage());
}
}
}
在上述代码中,try-with-resources
语句用于自动关闭文件读取器,这样即使发生异常,资源也会被正确释放。
当文件不存在时,会抛出FileNotFoundException
。我们通过catch
块捕获这个异常,并打印出错误信息。
还没有评论,来说两句吧...