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块
可以捕获多种类型的异常,但需注意子类异常应放在父类异常之前。
try {
// 可能抛出多种异常的代码
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("空指针异常: " + e.getMessage());
} catch (Exception e) {
System.out.println("通用异常: " + e.getMessage());
}
throws关键字
如果方法内部不处理异常,可以使用throws声明方法可能抛出的异常,由调用者处理。
public void readFile() throws IOException {
// 可能抛出IOException的代码
FileReader file = new FileReader("test.txt");
}
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);
}
}
// 使用自定义异常
try {
throw new CustomException("自定义异常");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
异常处理的最佳实践
- 避免捕获过于宽泛的异常(如直接捕获
Exception),应针对具体异常类型处理。 - 在
finally块中释放资源(如文件流、数据库连接)。 - 使用日志记录异常信息,便于调试和排查问题。
- 避免在循环中使用
try-catch块,可能影响性能。






