如何在Java中优雅地处理IO操作异常

原创 朱雀 2024-09-23 09:09 179阅读 0赞

在Java中,我们通常使用try-catch-finally语句来优雅地处理IO操作异常。以下是一个例子:

  1. import java.io.*;
  2. public class IOExceptionHandling {
  3. public static void main(String[] args) {
  4. try (FileReader fr = new FileReader("non_existent_file.txt")) {
  5. // 执行读取操作
  6. String content = fr.read();
  7. System.out.println(content);
  8. } catch (FileNotFoundException e) {
  9. // 处理文件不存在的异常
  10. System.err.println("File not found: " + e.getMessage());
  11. }
  12. }
  13. }

在上述代码中,try-with-resources语句用于自动关闭文件读取器,这样即使发生异常,资源也会被正确释放。

当文件不存在时,会抛出FileNotFoundException。我们通过catch块捕获这个异常,并打印出错误信息。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,179人围观)

还没有评论,来说两句吧...

相关阅读