首页 > 解决方案 > “错误:未报告的异常 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);
}

标签: java

解决方案


您可以使用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;

}

Java 尝试资源


推荐阅读