如何使用try catch以避免引发异常?

时间:2019-02-11 00:11:57

标签: java

我试图创建一个集合数据结构,并用我的类的构造函数中的字典文件中的所有单词填充它,但一直在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;
}
}

1 个答案:

答案 0 :(得分:0)

您的代码不会抛出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: ");
    }
}

当然,这取决于您要对文件对象执行的操作。