【发布时间】:2015-09-22 15:39:09
【问题描述】:
我正在尝试编写一个小程序,但遇到以下问题:
在我的一种方法中,我有以下代码
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。我在这里有点毫无意义,所以非常欢迎任何建议。
提前致谢
【问题讨论】:
-
Human#load未声明抛出FileNotFoundException。在load中,您吞下异常并返回null。它已经“处理”了。