【问题标题】:Exception supposedly never thrown even though it does at runtime应该不会抛出异常,即使它在运行时发生
【发布时间】: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。它已经“处理”了。

标签: java exception try-catch


【解决方案1】:

你的编译器抱怨这个:

try{
    rootHuman = Human.load(scanner.next());
}catch(FileNotFoundException f){
    //Missing Code              
}

在您的Human.load 方法中,您捕获了IOException,因此在方法“load”中永远不会抛出FileNotFoundException(witch 实际上是 IOException 的子类型),这个 catch 子句将始终处理它。

调用Human.load()时去掉try catch块:

 rootHuman = Human.load(scanner.next());

【讨论】:

  • 对,现在很明显了!!那么有没有可能将 catch 块从 load 方法移动到另一个位置?我只是因为风格原因才考虑这个,所以如果不是我也不会介意。
  • 你可以做到,只需删除catch子句catch(IOException i)并将方法重命名为:public static Human load(String filename) throws IOException但是,如果你有一个从文件系统加载文件的方法,你建议你catch尽快处理异常,并在出现问题时返回 null,就像你做的那样。
  • 好的,谢谢你真的帮助了我! (还不太习惯java)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2014-01-19
相关资源
最近更新 更多