为什么在读取数据时我们不需要使用try-catch块,但是在将Scanner附加到文件时我们确实需要try-catch?

时间:2022-09-20 13:44:52

Im reading a programming book on The Scanner, and it's saying that we don't need to use try-catch block when reading data because IOException are captured, but we do need try-catch when attaching a Scanner to a file.

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

for example, in the following code the try-catch is needed. Can you show me an example where try-catch isn't needed but the error is captured by IOException?

例如,在以下代码中需要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);
}

1 个解决方案

#1


0  

Can you show me an example where try-catch isn't needed but the error is captured by IOException?

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

Example:

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

These nextXXXmethods will not thrown any exception related to I/O as this is captured in the code.
They will throw an exception though if the input is exausted.
Read the Scanner Javadoc

这些nextXXX方法不会抛出与I / O相关的任何异常,因为这是在代码中捕获的。如果输入是exausted,他们将抛出异常。阅读Scanner Javadoc

#1


0  

Can you show me an example where try-catch isn't needed but the error is captured by IOException?

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

Example:

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

These nextXXXmethods will not thrown any exception related to I/O as this is captured in the code.
They will throw an exception though if the input is exausted.
Read the Scanner Javadoc

这些nextXXX方法不会抛出与I / O相关的任何异常,因为这是在代码中捕获的。如果输入是exausted,他们将抛出异常。阅读Scanner Javadoc