假设我有一个抛出异常的自定义阅读器对象:public StationReader { public StationReader(String inFile) throws FileNotFoundException { Scanner scan = new Scanner(inFile); while (scan.hasNextLine() { // blah blah blah } // Finish scanning scan.close(); }}我在另一个类 Tester 中调用 StationReader:public Tester { public static void main(String[] args) { try { StationReader sReader = new StationReader("i_hate_csv.csv"); } catch (FileNotFoundException e) { System.out.println("File not found arggghhhhhh"); } finally { // HOW TO CLOSE SCANNER HERE?? } }}现在让我们想象一下,在扫描这些行时,抛出了一个异常,因此scan.close()永远不会被调用。在这种情况下,如何关闭扫描仪对象?
1 回答
HUX布斯
TA贡献1876条经验 获得超6个赞
在try-with-resources语句中编写读取过程,但不要捕获任何异常,只需将它们传递回调用者即可,例如......
public class CustomReader {
public CustomReader(String inFile) throws FileNotFoundException {
try (Scanner scan = new Scanner(inFile)) {
while (scan.hasNextLine()) {
// blah blah blah
}
}
}
}
该try-with-resource语句会在代码存在try块时自动关闭资源
仅供参考:finally用于这个,但是当你有多个资源时,它变得凌乱。所有冰雹try-with-resources🎉
添加回答
举报
0/150
提交
取消
