简体   繁体   English

为什么在读取数据时不需要使用try-catch块,但是在将扫描仪附加到文件时却需要使用try-catch呢?

[英]Why is it that we don't need to use try-catch block when reading data but we do need try-catch when attaching a Scanner to a file?

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. 我正在阅读《扫描仪》上的一本编程书,这就是说,由于捕获了IOException,因此在读取数据时不需要使用try-catch块,但是在将扫描仪附加到文件时,我们需要使用try-catch。

for example, in the following code the try-catch is needed. 例如,在以下代码中,try-catch是必需的。 Can you show me an example where try-catch isn't needed but the error is captured by IOException? 您能给我看一个不需要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);
}

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 nextXXX methods will not thrown any exception related to I/O as this is captured in the code. 这些nextXXX方法不会引发任何与I / O相关的异常,因为这是在代码中捕获的。
They will throw an exception though if the input is exausted. 但是,如果输入被取消,它们将引发异常。
Read the Scanner Javadoc 阅读扫描仪Javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我们不必将 try-catch 添加到 RuntimeException? - Why we don't have to add try-catch to a RuntimeException? 我需要使用 try-catch,但它说这是一个无法访问的 catch 块。 我如何使它可达? - I need to use a try-catch, but it says it is an unreachable catch block. How do I make it reachable? 在我的示例中,为什么我需要尝试捕获? - Why do I need try-catch with throws in my example? Java:从文件读取时,扫描仪不接受try-catch类错误 - Java: Scanner not accepting try-catch class error when reading from file 扫描程序变量在try-catch块之外不起作用 - Scanner variable doesn't work outside the try-catch block try-catch语句在捕获异常时不返回try块 - try-catch statement not returning to try block when catching exception 在try-catch块之后有代码时,try-Catch不会重新运行 - Try-Catch does not rerun when there is code after the try-catch block Java,使用 Scanner 尝试捕获 - Java, try-catch with Scanner 为什么我的try-catch在捕获错误时会打印出错误和catch块? - Why does my try-catch when used to catch an error print out the error and my catch block? 我是否需要将所有saveOrUpdate方法包含在try-catch中? - Do I need to enclose all saveOrUpdate methods with try-catch?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM