【问题标题】:Catching FileNotFoundException. Problems with initializing Scanner prior to try/catch block捕获 FileNotFoundException。在 try/catch 块之前初始化 Scanner 的问题
【发布时间】:2019-10-03 11:54:37
【问题描述】:

我目前正在处理一些异常处理,但在使用驱动程序类时遇到了问题。驱动程序错误:“未报告的异常 java.io.FileNotFoundException;必须被捕获或声明为抛出。”我无法编辑驱动程序以将“抛出 FileNotFoundException”添加到 main。

这是来自主程序的代码 sn-p。我知道我需要使用 try/catch 来捕获异常,但我不知道如何在 try 块之前初始化 Scanner。

public program(String file1, String file2) throws FileNotFoundException
{
    File f1 = new File(file1);
    File f2 = new File(file2);

    try(Scanner scan = new Scanner(f1); Scanner scan2 = new Scanner(f2);) 
    {
    }
    catch(FileNotFoundException e){}

    int a = scan.nextInt(); //THIS IS WHERE I RUN INTO PROBLEMS (scan not found)
    scan.nextLine();
    int b = scan.nextInt();
}

【问题讨论】:

    标签: java exception-handling try-catch


    【解决方案1】:

    我通过删除“抛出 FileNotFoundException”来修复它

    public program(String file1, String file2)
    {
        try
        {
            File f1 = new File(file1);
            File f2 = new File(file2);
            int a = scan.nextInt(); //THIS IS WHERE I RUN INTO PROBLEMS (scan not found)
            scan.nextLine();
            int b = scan.nextInt();
        }
        catch(FileNotFoundException e){}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 2018-05-27
      • 1970-01-01
      • 2020-12-12
      相关资源
      最近更新 更多