从文本文件中读取字符时如何进行多个异常处理?

How to do multiple Exception handling while reading characters from a text file?

我在 Java 中提到了有关多个异常处理的早期线程。然而,当我尝试在我的代码中实现时,它无法编译。

try {
    br = new BufferedReader( new FileReader(file_name));
    while((r = br.read()) != -1){
        char c = (char) r;
        System.out.print(c);
} catch (FileNotFoundException e ){
    System.out.println("The file was not found.");
    System.exit(0);
} catch (IOException e){
    System.out.println("There was an error reading the file.");
    System.exit(0);
}

现在我知道 FileNotFoundException 是 IOException 的特例并且必须有多个 catch 块,这正是我正在做的,但是,编译器不允许我编译它。

您忘记 } 关闭 while 循环。请更正。 应该是这样的:

try {
    br = new BufferedReader( new FileReader(file_name));
    while((r = br.read()) != -1){
        char c = (char) r;
        System.out.print(c);
     }
} catch (FileNotFoundException e ){
    System.out.println("The file was not found.");
    System.exit(0);
} catch (IOException e){
    System.out.println("There was an error reading the file.");
    System.exit(0);
}

您的 try 语句缺少右括号:

    try {
            br = new BufferedReader( new FileReader(file_name));
            while((r = br.read()) != -1){
                char c = (char) r;
                System.out.print(c);
            }
    } catch (FileNotFoundException e ){
            System.out.println("The file was not found.");
            System.exit(0);
    } catch (IOException e){
                System.out.println("There was an error reading the file.");
                System.exit(0);
    }

你的 while 块没有关闭,那肯定是个问题。