java语言如何进行异常处理
异常处理的基本概念
Java中的异常处理机制用于捕获和处理程序运行时可能出现的错误或异常情况。异常分为检查型异常(Checked Exception)和非检查型异常(Unchecked Exception)。检查型异常需要在代码中显式处理,而非检查型异常(如运行时异常)通常由程序逻辑错误引起。
try-catch-finally 块
使用 try-catch-finally 结构捕获和处理异常。try 块包含可能抛出异常的代码,catch 块捕获并处理异常,finally 块用于执行无论是否发生异常都必须运行的代码。
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 捕获算术异常
System.out.println("除零错误: " + e.getMessage());
} finally {
// 无论是否发生异常都会执行
System.out.println("执行 finally 块");
}
多重 catch 块
可以针对不同类型的异常分别捕获和处理,多个 catch 块按顺序匹配异常类型。
try {
int[] arr = new int[5];
arr[10] = 50; // 抛出 ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("算术异常: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常: " + e.getMessage());
}
throws 关键字
如果方法内部不处理异常,可以通过 throws 声明方法可能抛出的异常,由调用者处理。
public void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
// 其他操作
}
throw 关键字
通过 throw 手动抛出异常,通常用于自定义异常或特定逻辑条件下的异常抛出。
public void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("年龄未满18岁");
}
}
自定义异常
通过继承 Exception 或 RuntimeException 创建自定义异常类。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public void validate(int value) throws CustomException {
if (value < 0) {
throw new CustomException("值不能为负数");
}
}
try-with-resources
Java 7 引入的语法,用于自动关闭实现了 AutoCloseable 接口的资源(如文件流、数据库连接等)。
try (FileReader fr = new FileReader("test.txt")) {
// 使用资源
} catch (IOException e) {
System.out.println("IO异常: " + e.getMessage());
}
异常链
通过构造方法或 initCause() 方法将异常链接起来,便于追踪异常根源。
try {
// 某些操作
} catch (IOException e) {
throw new CustomException("自定义异常", e);
}






