java - 如何使用 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;
}
}
解决方案
您的代码不会抛出 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: ");
}
}
当然,这取决于您要对文件对象做什么。
推荐阅读
- php - 我可以在 laravel-lighthouse 中抛出自定义错误吗
- python - NameError:名称“aic”未在 Arima 模型中定义
- facebook - Facebook像素域验证的同一域的多个验证
- sql - 使用 SQL 检索具有一定数量行的“页面”
- powershell - Powershell Invoke-WebRequest 返回 (401) Unauthorized
- mongodb - Mongodb $nin 不适用于嵌套数组
- python - 导出 Whatsapp 聊天
- laravel - Laravel 拒绝访问 /public 目录
- api - 如何在api上验证批量电子邮件?
- azure-devops - “配置触发器失败,再次编辑并保存管道”,没有明显错误,也没有更多详细信息