使用Java进行异常处理:多层捕获案例
在Java中,异常处理是通过try-catch-finally语句来实现的。下面是一个多层捕获的案例:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// 第一层捕获:可能会抛出IOException
File file = new File("non_existent_file.txt");
if (!file.exists()) {
System.out.println("File does not exist.");
} else {
System.out.println("File exists.");
}
// 第二层捕获:可能会在打开文件后抛出FileNotFoundException
BufferedReader reader = new BufferedReader(new FileReader(file)));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException | FileNotFoundException e) {
// 处理异常,打印错误信息
System.err.println("An error occurred:");
if (e instanceof IOException) {
System.err.println("IOException: " + e.getMessage());
} else if (e instanceof FileNotFoundException) {
System.err.println("FileNotFoundException: " + e.getMessage());
} else {
System.err.println("Unexpected exception: " + e.getMessage());
}
} finally {
// 只有finally块中的代码无论是否发生异常,都会被执行
System.out.println("Closing resources...");
}
}
}
在这个例子中,我们尝试读取一个不存在的文件。在try-catch语句中,我们使用了两层捕获:一层捕获可能抛出的IOException,另一层捕获可能在打开文件后抛出的FileNotFoundException。
如果发生异常,我们会打印详细的错误信息,并确保资源得到适当的关闭。
还没有评论,来说两句吧...