[英]Java program gives me FileNotFoundException when the file I am reading from exists but then works perfectly fine if I handle the exception
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordJumble {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File file = new File("F:/Files/Topic.txt");
Scanner sc = new Scanner(file);
String title = sc.nextLine();
System.out.println(title);
for(int i=0;i<10;i++){
System.out.println(sc.nextLine());
}
}
}
Currently the program does what I want it to, but why is it giving me an error about the file not existing? 目前,该程序可以实现我想要的功能,但是为什么会给我有关该文件不存在的错误的信息? When I add the throws
clause to ignore the error it is able to find the file without issue. 当我添加throws
子句以忽略该错误时,它便能够毫无问题地找到该文件。
While the wording of the error may be a little confusing, the error isn't a FileNotFoundException in and of itself but is instead a complaint that you aren't dealing with the possibility of such an exception being thrown. 尽管错误的措辞可能有点令人困惑,但该错误本身并不是FileNotFoundException,而是抱怨您没有处理抛出此类异常的可能性 。 All your compiler is telling you is that you need to deal with the possibility of the file not being where you think it is. 编译器告诉您的是,您需要处理该文件不在您认为的位置的可能性。 Therefore, when you add throws FileNotFoundException
to the method signature the compiler is satisfied and your error goes away. 因此,当您向方法签名添加throws FileNotFoundException
,编译器将得到满足,并且错误将消失。
When you said 'add the statement to ignore the error' you meant adding the 'throws...' clause to the definition of main
so it would compile cleanly. 当您说“添加语句以忽略错误”时,您的意思是在main
的定义中添加“ throws ...”子句,以便可以进行干净地编译。 Right? 对?
What's going on is that Scanner
many throw a FileNotFoundException
if the file is not found. 发生的情况是,如果找不到该文件,许多Scanner
抛出FileNotFoundException
。 This exception must be handled (caught) somewhere. 必须在某个地方处理(捕获)此异常。
Instead, you elected not to handle, and said that it could propagate out from main
. 相反,您选择不处理,并说它可以从main
传播出去。
The appropriate way to do this is use a try - catch
construction. 做到这一点的适当方法是使用try - catch
结构。
try {
Scanner sc = new Scanner(file);
:
:
catch (FileNotFoundException ex) {
... print an error or something ...
}
This sort of approach is used so that the error handling is 'out of line' of the main flow of the code. 使用这种方法是为了使错误处理在代码主流中“与众不同”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.