如何捕获java异常
捕获Java异常的基本方法
使用try-catch块是Java中捕获异常的核心机制。将可能抛出异常的代码放入try块中,通过catch块捕获并处理异常。
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 处理算术异常
System.out.println("除数不能为零");
}
多重catch块的使用
当代码可能抛出多种异常时,可以通过多个catch块分别处理不同类型的异常。异常捕获的顺序应从具体到一般。
try {
// 可能抛出多种异常的代码
int[] arr = new int[5];
arr[10] = 20;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常");
} catch (Exception e) {
System.out.println("其他异常");
}
finally块的作用
finally块用于执行无论是否发生异常都必须运行的代码,常用于资源释放等清理工作。

try {
// 可能抛出异常的代码
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到");
} finally {
System.out.println("资源清理");
}
异常信息的获取
通过异常对象可以获取详细的异常信息,包括异常类型、消息和堆栈轨迹。
try {
// 可能抛出异常的代码
Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("异常类型: " + e.getClass().getName());
System.out.println("异常消息: " + e.getMessage());
e.printStackTrace();
}
自定义异常的处理
通过继承Exception类可以创建自定义异常,并在代码中抛出和捕获。

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
对于实现了AutoCloseable接口的资源,可以使用try-with-resources语法自动关闭资源,无需显式调用close()方法。
try (FileInputStream file = new FileInputStream("test.txt")) {
// 使用文件资源
} catch (IOException e) {
System.out.println("IO异常");
}
异常的传播与重新抛出
异常可以在捕获后被重新抛出,或者包装成其他类型的异常后抛出。
try {
// 可能抛出异常的代码
someMethod();
} catch (SQLException e) {
throw new RuntimeException("数据库操作失败", e);
}
通过合理使用这些方法,可以有效地捕获和处理Java程序中的异常,确保程序的健壮性和稳定性。






