Java 错误:默认构造函数无法处理异常类型 FileNotFound 异常 [英] Java error: Default constructor cannot handle exception type FileNotFound Exception
问题描述
我正在尝试从文件中读取输入以将其放入 Java 小程序以显示为吃豆人级别,但我需要使用类似于 getLine() 的东西...所以我搜索了类似的东西,这是我找到的代码:
I'm trying to read input from a file to be taken into a Java applet to be displayed as a Pac-man level, but I need to use something similar to getLine()... So I searched for something similar, and this is the code I found:
File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
我标记为ERROR"的那一行给了我一个错误,提示默认构造函数无法处理隐式超级构造函数抛出的异常类型 FileNotFoundException.必须定义一个显式构造函数."
The line I marked "ERROR" gives me an error that says "Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor."
我已经搜索过此错误消息,但我发现的所有内容似乎都与我的情况无关.
I've searched for this error message, but everything I find seems to be unrelated to my situation.
推荐答案
要么在您的子类中声明一个显式构造函数,该构造函数抛出 FileNotFoundException
:
Either declare a explicit constructor at your subclass that throws FileNotFoundException
:
public MySubClass() throws FileNotFoundException {
}
或者用 try-catch
块包围基类中的代码,而不是抛出 FileNotFoundException
异常:
Or surround the code in your base class with a try-catch
block instead of throwing a FileNotFoundException
exception:
public MyBaseClass() {
FileInputStream fstream = null;
try {
File inFile = new File("textfile.txt");
fstream = new FileInputStream(inFile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// Do something with the stream
} catch (FileNotFoundException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
try {
// If you don't need the stream open after the constructor
// else, remove that block but don't forget to close the
// stream after you are done with it
fstream.close();
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
无关,但由于您正在编写 Java 小程序,请记住您需要 签名 以执行 IO 操作.
Unrelated, but since you are coding a Java applet, remember that you will need to sign it in order to perform IO operations.
这篇关于Java 错误:默认构造函数无法处理异常类型 FileNotFound 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!