java如何使用异常
异常处理基础
Java异常处理通过try-catch-finally机制实现。将可能抛出异常的代码放入try块,通过catch捕获并处理异常,finally块用于执行必须的清理操作(无论是否发生异常都会执行)。
try {
// 可能抛出异常的代码
int result = 10 / 0; // 抛出ArithmeticException
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
} finally {
System.out.println("清理资源");
}
异常类型
- 受检异常(Checked Exception):编译时强制检查,必须处理(如
IOException)。 - 非受检异常(Unchecked Exception):包括运行时异常(如
NullPointerException)和错误(如OutOfMemoryError),通常不强制处理。
// 受检异常需显式处理
try {
FileReader file = new FileReader("test.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到");
}
抛出异常
通过throw主动抛出异常,或在方法签名中使用throws声明可能抛出的异常。
// 抛出异常
void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
}
// 声明异常
void readFile() throws IOException {
Files.readAllLines(Paths.get("file.txt"));
}
自定义异常
继承Exception或RuntimeException创建自定义异常类。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用示例
try {
throw new CustomException("自定义异常");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
异常链
通过initCause()或构造方法传递原始异常,保留完整的异常信息。
try {
// 模拟原始异常
throw new NullPointerException();
} catch (NullPointerException e) {
IllegalStateException ex = new IllegalStateException("包装异常");
ex.initCause(e);
throw ex;
}
try-with-resources
自动管理资源(实现AutoCloseable接口的类),无需显式调用close()。
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
}
最佳实践
- 避免捕获过于宽泛的异常(如直接捕获
Exception),应针对具体异常类型处理。 - 在
finally块中释放资源,或使用try-with-resources简化代码。 - 日志记录异常信息(如
e.printStackTrace()或日志框架)。 - 自定义异常时提供有意义的错误信息。






