首页 > 解决方案 > 如何使用 try catch 来避免抛出异常?

问题描述

我试图在我的类的构造函数中创建一个集合数据结构并用字典文件中的所有单词填充它,但在 FileNotFoundException 部分不断出现错误:

public class CaesarCipher {

public CaesarCipher()  {
    try {
    File dict = new File("dictionary/google10000.txt");
    }
    catch (FileNotFoundException e) {
        System.out.println("File does not exist, please try again: ");
    }
}
public String decode(String s) {
    String [] word = s.split("");
    Set<String> dict = new HashSet<String>();
    return null;
}
}

标签: java

解决方案


您的代码不会抛出 FileNotFoundException,因为您没有使用 File 对象。但是,假设您要读取该文件,如果在 File 对象实例化后添加以下代码行,您的编译器将不会报错。

public CaesarCipher()  {
    try {
        File dict = new File("dictionary/google10000.txt");
        FileInputStream inputStream = new FileInputStream(dict);
    }
    catch (FileNotFoundException e) {
        System.out.println("File does not exist, please try again: ");
    }
}

当然,这取决于您要对文件对象做什么。


推荐阅读