Java 错误:默认构造函数无法处理异常类型 FileNotFound Exception
我正在尝试从文件中读取输入,并将其放入 Java 小程序中,以显示为吃豆人关卡,但我需要使用类似于 getLine() 的东西...所以我搜索了类似的东西,这是我找到的代码:
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));
我标记为“错误”的行给出了一个错误,指出“默认构造函数无法处理隐式超级构造函数抛出的异常类型 FileNotFoundException。必须定义显式构造函数。”
我已经搜索过此错误消息,但我发现的所有内容似乎与我的情况无关。
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));
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要么在子类中声明一个抛出
FileNotFoundException
的显式构造函数:或者用
try-catch
块包围基类中的代码,而不是抛出FileNotFoundException
code> 异常:不相关,但由于您正在编写 Java 小程序,请记住您需要 对其进行签名以便执行IO操作。
Either declare a explicit constructor at your subclass that throws
FileNotFoundException
:Or surround the code in your base class with a
try-catch
block instead of throwing aFileNotFoundException
exception:Unrelated, but since you are coding a Java applet, remember that you will need to sign it in order to perform IO operations.
您需要用 try 和 catch 包围您的代码,如下所示:
You need to surround your code with try and catch as follows:
这是猜测,因为我们没有完整的代码。
来自 Javadoc:
这意味着当您像您一样执行新的
FileInputStream()
时,它可能会返回FileNotFoundException
。这是一个已检查的异常,您需要重新抛出(即在执行 new 的方法中添加“抛出 FileNotFoundException”)或捕获(请参阅其他 try/catch 响应)。This is guesswork as we don't have the complete code.
From the Javadoc:
It means that when you do a new
FileInputStream()
like you do, it can come back with aFileNotFoundException
. This is a checked exception, that you need to either rethrow (i.e. add 'throws FileNotFoundException' in the method where you do the new) or catch (see other try/catch responses).