use*_*058 6 java try-catch filenotfoundexception
我有一些命令在磁盘上创建一个文件.因为必须在其中创建文件的文件夹是动态的,所以我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
您遇到的特定问题也可能不是FileNotFoundException。通过在catch块(所有Exception的父类)中使用“ Exception”,这实际上是“全部捕获”,因为如果抛出“ Exception”或其任何子类,它将运行。
尝试以下更改:
...
catch (Exception e) {
System.out.println(e.getClass());
}
...
Run Code Online (Sandbox Code Playgroud)
这将告诉您此块捕获的Exception的特定类。我敢打赌,您会发现Exception实际上是一个子类的实例(例如IOException)。