![](/img/trans.png)
[英]Why we don't have to add try-catch to a RuntimeException?
[英]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?
我正在阅读《扫描仪》上的一本编程书,这就是说,由于捕获了IOException,因此在读取数据时不需要使用try-catch块,但是在将扫描仪附加到文件时,我们需要使用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);
}
您能给我看一个不需要try-catch但错误被IOException捕获的示例吗?
例:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
这些nextXXX
方法不会引发任何与I / O相关的异常,因为这是在代码中捕获的。
但是,如果输入被取消,它们将引发异常。
阅读扫描仪Javadoc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.