Java异常处理:捕获、处理和抛出示例
在Java中,异常是一种程序运行时可能出现的问题。通过异常处理机制,我们可以优雅地捕获、处理这些异常情况。
下面是一些基本的Java异常处理示例:
- 捕获并打印异常
try {
int divByZero = 5 / 0; // 这会抛出ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero caught.");
e.printStackTrace(); // 打印堆栈跟踪信息,便于调试
}
- 使用finally块进行资源清理
try {
File file = new File("non_existent_file.txt");
FileReader reader = new FileReader(file);
// 读取文件内容
} catch (FileNotFoundException e) {
System.out.println("Error: Could not find specified file.");
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close(); // 关闭资源,防止泄露
}
if (file != null && !file.delete()) {
System.out.println("Warning: Failed to delete non-existent file.");
}
// 清理其他资源
} catch (IOException ioe) {
System.out.println("Error: Could not close or delete resources.");
ioe.printStackTrace();
}
}
以上就是Java中异常处理的一些基本示例。在实际开发中,根据业务需求和异常类型进行更复杂的设计和处理。
还没有评论,来说两句吧...