在Java中使用Readers和Streams总是让我感到困惑的一件事是该close()
方法可以抛出异常.因为将close方法放在finally块中是个好主意,这需要一些尴尬的情况.我通常使用这种结构:
FileReader fr = new FileReader("SomeFile.txt");
try {
try {
fr.read();
} finally {
fr.close();
}
} catch(Exception e) {
// Do exception handling
}
Run Code Online (Sandbox Code Playgroud)
但我也看到了这种结构:
FileReader fr = new FileReader("SomeFile.txt");
try {
fr.read()
} catch (Exception e) {
// Do exception handling
} finally {
try {
fr.close();
} catch (Exception e) {
// Do exception handling
}
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢第一个结构,因为只有一个挡块,它看起来更优雅.是否有理由更喜欢第二种或替代结构?
更新:如果我指出两者read
并且close
只抛出IOExceptions ,它会有所作为吗?因此,在我看来,如果读取失败,关闭将因同样的原因而失败.