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

标签 java exception 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。显然,构造函数与存储初始化属于不同的类。 这应该很容易回答我只是遗漏了一些东西。

最佳答案

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

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/

相关文章:

java - Apache Batik SVG 转 PDF - 输出 PDF 大小不正确

java - 使用图形 API 的 Azure AD 导入适用于随机应用程序

java - 如何在不知道格式的情况下映射 json 对象的值?

java - 可以获取、放置和删除 HashMap 中的元素而无需迭代导致 ConcurrentModificationException?

java - 使用JAVA形成测试数据列表进行selenium功能测试

java - 使用来自 javascript 的索引获取 spring 模型属性列表元素

Python 异常处理 - 最佳实践

java - 在 AsyncTask 中捕获未处理异常的设计模式

ruby-on-rails-3 - 如何测试 RSpec 中的参数计数?

java - 在 Java 8 中构建 Map 以进行集成测试的重构方法 - 函数式编程的机会?