java 如何获取异常
获取异常的方法
在Java中,异常处理主要通过try-catch块实现。以下是获取异常信息的几种常见方式:
捕获异常并打印堆栈信息
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
e.printStackTrace(); // 打印异常堆栈信息
}
获取异常的具体信息
try {
// 可能抛出异常的代码
String str = null;
str.length();
} catch (NullPointerException e) {
System.out.println("异常信息: " + e.getMessage()); // 获取异常描述
}
自定义异常处理逻辑

try {
// 可能抛出异常的代码
int[] arr = new int[5];
arr[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("数组越界: " + e.toString()); // 获取异常类型和描述
}
使用多重catch块处理不同类型的异常
try {
// 可能抛出多种异常的代码
FileInputStream file = new FileInputStream("nonexistent.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
}
使用finally块确保资源释放

try {
// 可能抛出异常的代码
Connection conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println("数据库异常: " + e.getMessage());
} finally {
// 无论是否发生异常都会执行的代码
System.out.println("清理资源");
}
获取异常的完整信息
对于需要记录或分析异常的场景,可以获取更详细的异常信息:
try {
// 业务代码
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
System.out.println("完整异常信息:\n" + exceptionAsString);
}
抛出自定义异常
在方法中主动抛出异常:
public void validateAge(int age) throws InvalidAgeException {
if (age < 0) {
throw new InvalidAgeException("年龄不能为负数");
}
}
异常链
捕获异常后重新抛出并保留原始异常信息:
try {
// 业务代码
} catch (SQLException e) {
throw new BusinessException("数据库操作失败", e);
}
这些方法覆盖了Java中处理异常的主要场景,从基本的捕获打印到高级的异常传递和自定义处理。根据具体需求选择合适的异常处理方式。






