![](/img/trans.png)
[英]Works fine without ItemListener, but when I add it, it gives me a NullPointerException
[英]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());
}
}
}
目前,该程序可以实现我想要的功能,但是为什么会给我有关该文件不存在的错误的信息? 当我添加throws
子句以忽略该错误时,它便能够毫无问题地找到该文件。
尽管错误的措辞可能有点令人困惑,但该错误本身并不是FileNotFoundException,而是抱怨您没有处理抛出此类异常的可能性 。 编译器告诉您的是,您需要处理该文件不在您认为的位置的可能性。 因此,当您向方法签名添加throws FileNotFoundException
,编译器将得到满足,并且错误将消失。
当您说“添加语句以忽略错误”时,您的意思是在main
的定义中添加“ throws ...”子句,以便可以进行干净地编译。 对?
发生的情况是,如果找不到该文件,许多Scanner
抛出FileNotFoundException
。 必须在某个地方处理(捕获)此异常。
相反,您选择不处理,并说它可以从main
传播出去。
做到这一点的适当方法是使用try - catch
结构。
try {
Scanner sc = new Scanner(file);
:
:
catch (FileNotFoundException ex) {
... print an error or something ...
}
使用这种方法是为了使错误处理在代码主流中“与众不同”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.