【问题标题】:JAVA + try catch(FileNotFoundException e) going in catch(Exception e)?JAVA + try catch(FileNotFoundException e) 进入 catch(Exception e)?
【发布时间】:2011-05-05 13:42:06
【问题描述】:

我有一些命令可以在磁盘上创建一个文件。 因为必须在其中创建文件的文件夹是动态的,所以我有一个 catch(FileNotFoundException e)。在同一个 try 块中,我已经有一个 catch(Exception e) 块。 出于某种原因,当我运行我的代码并且该文件夹还不存在时,使用了 catch(Exception e) 块,而不是 FileNotFoundException 块。

调试器很清楚(至少对我而言),显示 FileNotFoundException: java.io.FileNotFoundException: c:\mydata\2F8890C2-13B9-4D65-987D-5F447FF0DDA7\filename.png (系统找不到路径指定)

知道为什么它不进入 FileNotFoundException 块吗? 谢谢;

代码:

import java.io.FileNotFoundException;

try{
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle screenRectangle = new Rectangle(screenSize);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRectangle);
    ImageIO.write(image, "png", new File(fileName));
}
catch (FileNotFoundException e){
    // do stuff here..
    return false;
}
catch(Exception e){
    // do stuff here..
    return = false;
}

【问题讨论】:

  • 如果您发布遇到问题的实际代码 sn-p 将会很有帮助。还要确保您导入的 FileNotFoundException 与抛出的相同。有时,如果您的类路径上有另一个库也有 FileNotFoundException,您的 IDE 可能会导入错误的包。不太可能,但重要的是首先排除这种可能性。
  • 请同时发布代码和堆栈跟踪。
  • 应该可以。执行@normalocity 建议的操作以确认异常类名称。我冒昧地猜测它可能是一般的 IOException。

标签: java try-catch filenotfoundexception


【解决方案1】:

您遇到的具体问题也可能不是 FileNotFoundException。通过在 catch 块(它是所有异常的父类)中使用“异常”,这实际上是一个“全部捕获”,因为如果抛出了“异常”或其任何子类,它将运行。

尝试以下更改:

...

catch (Exception e) {
  System.out.println(e.getClass());
}
...

这将告诉您该块捕获的异常的特定类。我敢打赌,您会发现 Exception 实际上是子类的一个实例(例如 IOException)。

【讨论】:

    【解决方案2】:

    您的问题是 FileNotFoundException 被抛出 java 库深处的某个地方并且没有传播,因此您无法捕获它。 这里真正的罪魁祸首是一个 NullPointerException 源自

    ImageIO.write(image, "png", new File(fileName));
    

    打电话。这个会碰到你的catch (Exception e) 块。
    如果您在常规异常捕获之前添加catch (NullPointerException e) 块,您会看到它在其中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-04
      • 2010-12-14
      • 2020-07-26
      • 1970-01-01
      • 2021-07-10
      • 2014-03-18
      • 2021-04-17
      相关资源
      最近更新 更多