gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:12:57 25 4
gpt4 key购买 nike

我已经提到了有关 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 block ,这正是我正在做的事情,但是编译器不允许我编译它。

最佳答案

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

关于java - 从文本文件读取字符时如何进行多个异常处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31504223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com