捕获FileNotFoundException。在try / catch块之前初始化Scanner的问题

时间:2017-02-17 02:54:24

标签: java exception-handling try-catch

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

以下是主程序的代码片段。我知道我需要用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();
}

1 个答案:

答案 0 :(得分:0)

我通过删除"修复了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){}
}