为什么构造函数处理异常但我在使用它时得到 "not handled exception error"

Why does the constructor handle the exception but I get a "not handled exception error" when I use it

我有两个构造函数:

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 尚未处理。显然,构造函数与存储初始化处于不同的 class 中。 这应该很容易回答我只是遗漏了一些东西。

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 子句。

尝试删除 Throw 语句