我有两个构造函数:
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
。显然,构造函数与存储初始化属于不同的类。
这应该很容易回答我只是遗漏了一些东西。
最佳答案
throws
和 catch
是不同的。
当一个方法在其签名中声明它抛出
一个异常时,调用者必须通过重新抛出或捕获它来处理它。
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
子句。
关于java - 为什么构造函数处理异常但我在使用它时得到 "not handled exception error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48975094/