我有两个构造函数:
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
尚未处理。显然,构造函数与商店初始化不同。
这应该很容易回答我只是缺少一些东西。
答案 0 :(得分:2)
throws
和catch
不同。
当一个方法在其签名中声明它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语句