【发布时间】:2019-03-27 15:47:19
【问题描述】:
我看到了这个使用FileInuputStream和FileOutputStream的例子:
try (FileInputStream in = new FileInputStream("./TestDir/IOfile.txt");
FileOutputStream out = new FileOutputStream("./TestDir/IOfile_out.txt")) {
// Do something...
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我省略了// Do something...的部分,因为即使所有这些操作都消失了,也会发生这个问题。
既然FileInputStream和FileOutputStream的构造函数可能会抛出FileNotFoundException,我可以理解为什么要抓FileNotFoundException。
但是捕获IOException 的依据是什么?好像没有它编译器不会让它工作,我不知道我怎么知道这是需要的。
【问题讨论】:
-
close方法被a try-with-resources调用会抛出IOException -
你不只是阅读一个文件,你
write()一个不同的文件。写入可能会导致IOException,也许是在您没有路径上的写入权限的情况下。见JavaDocs:write(...) throws IOException。顺便说一句,@CarlosHeuberger 也是对的。 -
但是没有必要捕捉
FileNotFoundException,因为你已经捕捉到IOException -
@deHaar 但是这个块中没有写
close()方法。是不是因为我用了try(){}作为try-with-resource的编码方式,所以隐含了close()? -
我还没有写任何关于 close 方法的东西......但是它被 try with resources 隐式使用。
标签: java exception try-with-resources