java - “错误:未报告的异常 FileNotFoundException;必须被捕获或声明为抛出”在返回行,不知道如何摆脱它
问题描述
返回扫描仪时,我在最后一行代码中收到此错误。我不能使用 throw,所以我需要在代码中保留 try catch。
public static Scanner getInputScanner(Scanner console) {
boolean inputTest = true;
File inputFile = null;
System.out.print("Enter input file: ");
while(inputTest){
try{
inputFile = new File(console.next());
Scanner input = new Scanner(inputFile);
inputTest = false;
}catch (FileNotFoundException e) {
System.out.println("File does not exist");
System.out.print("Enter new input file: ");
inputTest = true;
continue;
}
}
return new Scanner(inputFile);
}
解决方案
您可以使用try With Resources
来读取文件。Java try with resources 构造,AKA Java try-with-resources,是一种异常处理机制,可以在您使用完资源后自动关闭资源,例如 Java InputStream 或 JDBC Connection。为此,您必须在 Java try-with-resources 块中打开并使用该资源。当执行离开 try-with-resources 块时,在 try-with-resources 块中打开的任何资源都会自动关闭,无论是否从 try-with-resources 块内或尝试关闭时抛出任何异常资源
public static Scanner getInputScanner(Scanner console) throws IOException {
try (FileInputStream fileInputStream = new FileInputStream(console.next())) {
return new Scanner(fileInputStream);
} catch (FileNotFoundException exception) {
exception.printStackTrace();
}
return null;
}
推荐阅读
- mysql - 查询有效,但需要很长时间才能执行
- vba - 仅当它存在于工作簿中时才选择活动工作表
- android - Android远程查看未决意图不起作用
- wordpress - 仅在后端强制 HTTP WordPress 多站点
- javascript - 如何使用 TypeScript 从包装的组件中访问公共方法?
- python - 混淆矩阵 - 奇怪的数字输出
- docker - 提交后无法访问 Docker 容器
- javascript - SVG路径的绘制不是从0开始
- spring - 如何在我的 Spring Boot 应用程序中处理 HTTP 429?
- keras - 使用生成器在 Tensorboard 中说明批处理