据称从未抛出异常,即使它在运行时抛出
Exception supposedly never thrown even though it does at runtime
我正在尝试编写一个小程序,但遇到了以下问题:
在我的一种方法中,我有以下代码
try{
rootHuman = Human.load(scanner.next());
}catch(FileNotFoundException f){
//Missing Code
}
我在其中尝试捕获 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条款会一直处理的。
删除调用时的try catch块Human.load()
:
rootHuman = Human.load(scanner.next());
我正在尝试编写一个小程序,但遇到了以下问题:
在我的一种方法中,我有以下代码
try{
rootHuman = Human.load(scanner.next());
}catch(FileNotFoundException f){
//Missing Code
}
我在其中尝试捕获 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条款会一直处理的。
删除调用时的try catch块Human.load()
:
rootHuman = Human.load(scanner.next());