0

我正在阅读一本关于 The Scanner 的编程书,它说我们在读取数据时不需要使用 try-catch 块,因为捕获了 IOException,但是在将 Scanner 附加到文件时我们确实需要 try-catch。

例如,在下面的代码中需要 try-catch。你能告诉我一个不需要try-catch但错误被IOException捕获的例子吗?

Scanner scnaFile = null;
String fileName = "dataFile.txt";
try{
    scanFile = new Scanner(new File(fileName));
} catch (FileNotFoundException ex){
     System.err.println(filename + " not found");
     System.exit(1);
}
4

1 回答 1

0

你能告诉我一个不需要try-catch但错误被IOException捕获的例子吗?

例子:

Scanner sc = new Scanner(new File("myNumbers"));  
while (sc.hasNextLong()) {  
   long aLong = sc.nextLong();  
}  

这些nextXXX方法不会抛出任何与 I/O 相关的异常,因为这是在代码中捕获的。
如果输入耗尽,它们会抛出异常。
阅读扫描仪 Javadoc

于 2012-10-12T20:51:02.090 回答