Java异常处理:捕获和重新抛出
在Java中,异常是一种中断程序正常流程的情况。当我们遇到无法预料或者不应该发生的操作时,就会产生异常。
为了处理这些异常,我们可以使用try-catch-finally结构:
// 假设我们要读取一个文件
try {
File file = new File("filename.txt");
// 读取文件可能会抛出IOException
String content = new BufferedReader(new FileReader(file))).readLine();
System.out.println(content); // 打印文件内容
} catch (FileNotFoundException e) {
// 文件未找到异常
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
// 读取文件时的其他IO异常
System.out.println("Error reading file: " + e.getMessage());
} finally {
// 不论是否捕获到异常,finally块中的代码总是会执行的
System.out.println("Operation completed, regardless of exceptions.");
}
在上述示例中,我们首先尝试读取一个文件。如果在try块中发生任何IOException,那么就会立即跳转到catch块中处理该异常。
无论是否捕获到特定类型的异常,finally块中的代码始终会执行。这通常是用于清理资源或提供程序结束的声明。
还没有评论,来说两句吧...