java如何处理异常
异常处理的基本概念
Java中的异常处理通过try-catch-finally机制实现,用于捕获和处理程序运行时可能出现的错误或异常情况。异常分为检查型异常(必须处理)和非检查型异常(如运行时异常)。
使用try-catch块
通过try块包裹可能抛出异常的代码,catch块捕获并处理特定类型的异常:
try {
int result = 10 / 0; // 抛出ArithmeticException
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
多异常捕获
可以捕获多种异常类型,或使用|合并处理:
try {
// 可能抛出多种异常的代码
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
System.out.println("空指针或数组越界: " + e.getMessage());
}
finally块的使用
无论是否发生异常,finally块中的代码都会执行,常用于资源释放:
FileInputStream file = null;
try {
file = new FileInputStream("test.txt");
// 文件操作
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println("关闭文件失败: " + e.getMessage());
}
}
}
抛出异常
通过throw主动抛出异常,或在方法声明中使用throws标记可能抛出的异常:
public void checkAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
}
自定义异常
继承Exception或RuntimeException创建自定义异常类:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用示例
try {
throw new CustomException("自定义异常示例");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
try-with-resources
Java 7+支持自动资源管理,适用于实现了AutoCloseable接口的资源:
try (FileInputStream file = new FileInputStream("test.txt")) {
// 自动关闭文件流
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
}
异常链
通过initCause()或构造方法传递原始异常信息:
try {
// 可能抛出异常的代码
} catch (IOException e) {
throw new CustomException("高层异常").initCause(e);
}
最佳实践
- 避免捕获过于宽泛的异常(如直接捕获
Exception)。 - 优先使用具体的异常类型以提高代码可读性。
- 在日志中记录异常堆栈(
e.printStackTrace()或日志框架)。 - 清理资源时确保
finally块或try-with-resources的正确使用。







