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

时间:2015-07-19 17:58:58

标签: java exception exception-handling bufferedreader

我之前提到过有关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块,这正是我正在做的事情,但是,编译器不允许我编译它。

3 个答案:

答案 0 :(得分:2)

您忘记}关闭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);
}

答案 1 :(得分:1)

你错过了你的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);
    }

答案 2 :(得分:1)

您的while块未关闭,这肯定是个问题。