为什么构造函数处理异常但我在使用它时遇到“未处理的异常错误”

时间:2018-02-25 15:21:42

标签: java exception-handling hashmap

我有两个构造函数:

protected WordStore() {
    this.bigMap = new HashMap<>();
}

protected WordStore(String file) throws IOException {
    this.bigMap = new HashMap<>();
    String line = "";
    try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file));)
    {
        while ( (line = bufferedReader.readLine()) != null){
            System.out.print(line);
            }
    }
    catch (IOException e) {
        System.out.println("The file could not have been loaded correctly");
        }
    }

第二个处理IOexception并且它正确编译但是当我尝试从WordStore初始化新地图时:

WordStore store1 = new WordStore("text.txt");

我收到编译错误,指出IOException尚未处理。显然,构造函数与商店初始化不同。 这应该很容易回答我只是缺少一些东西。

2 个答案:

答案 0 :(得分:2)

throwscatch不同。 当一个方法在其签名中声明它throws一个异常时,调用者必须通过重新抛出它或捕获它来处理它。

protected WordStore(String file) throws IOException {
 //doing something that can throw an IOException
}

//Caller handles it
try {
    new WordStore("text.txt");
} catch (IOException ioex) {
    //Handle the exception
}

//Or the caller (Assuming the caller is the main method) can throw it back
public static void main(String[] args) throws IOException {
    new WordStore("text.txt");
}

此处,由于您已经捕获IOException,因此可以从构造函数中删除throws子句。

答案 1 :(得分:1)

尝试删除Throw语句