我正在尝试编写一个小程序,但遇到了以下问题:
在我的一个方法中,我有以下代码
try{
rootHuman = Human.load(scanner.next());
}catch(FileNotFoundException f){
//Missing Code
}
我 try catch FileNotFoundException。所以看看 Human.load() 的函数调用,我们有这段代码
public static Human load(String filename){
try{
Human human;
FileInputStream fileIn = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fileIn);
human = (Human) in.readObject();
in.close();
fileIn.close();
return human;
}catch(IOException i){
i.printStackTrace();
return null;
}catch(ClassNotFoundException c){
c.printStackTrace();
return null;
}
当尝试在这里捕获 FileNotFoundException 时,我也遇到了同样的问题。我的问题是编译器告诉我永远不会抛出此异常,但是当我执行代码时,当 Scanner.next() 的输入是不存在的文件名时,我显然可以得到 FileNotFoundException 。我在这里毫无意义,所以非常欢迎任何建议。
提前致谢
最佳答案
你的编译器提示这一点:
try{
rootHuman = Human.load(scanner.next());
}catch(FileNotFoundException f){
//Missing Code
}
在您的 Human.load
方法中,您捕获了 IOException
,因此 FileNotFoundException
(女巫实际上是 IOException 的子类型)将永远不会被抛出到方法“load”中,这个 catch 子句将始终处理它。
调用Human.load()
时删除try catch block :
rootHuman = Human.load(scanner.next());
关于java - 即使在运行时抛出异常,据说也不会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32721157/