Java异常处理机制
异常定义
Java将程序执行过程中的非正常行为定义为异常。例如:
int result = 10 / 0; // 抛出ArithmeticException
int[] arr = new int[3];
System.out.println(arr[5]); // 抛出ArrayIndexOutOfBoundsException
String str = null;
System.out.println(str.length()); // 抛出NullPointerException
每种异常类型均由特定类描述,如ArithmeticException对应算术错误。
异常体系
异常分类体系基于Throwable类:
- Error: JVM无法处理的严重问题(如
OutOfMemoryError) - Exception: 可通过代码处理的异常,分为:
- 运行时异常(非受查):继承
RuntimeException,运行后触发 - 编译时异常(受查):直接继承
Exception,编译时检测
- 运行时异常(非受查):继承
异常处理方式
防御式编程
- LBYL: 操作前检查(易导致代码冗余)
- EAFP: 先操作后处理(推荐,分离主逻辑与错误处理)
异常抛出
使用throw手动抛出异常:
public class Validator {
public static void checkArray(int[] data) {
if (data == null) {
throw new IllegalStateException("数组为空");
}
}
}
运行时异常可忽略处理;编译时异常必须显式处理。
异常声明
通过throws声明编译时异常,交由调用方处理:
public class Processor {
public static void validate(int[] data) throws IOException {
if (data.length == 0) {
throw new IOException("数据无效");
}
}
}
多异常声明时用逗号分隔类型。
异常捕获
使用try-catch处理异常:
try {
System.out.println(10 / 0);
} catch (ArithmeticException ex) {
ex.printStackTrace();
System.out.println("算术异常已处理");
} catch (Exception ex) {
System.out.println("未知异常");
}
多个catch块按子类到父类排序。
finally确保资源释放:
Scanner input = new Scanner(System.in);
try {
int num = input.nextInt();
} catch (InputMismatchException ex) {
System.out.println("输入格式错误");
} finally {
input.close();
System.out.println("资源已释放");
}
自定义异常
继承Exception或RuntimeException创建定制异常:
public class InvalidCredentialException extends RuntimeException {
public InvalidCredentialException(String message) {
super(message);
}
}
登录验证示例:
public class AuthService {
private final String USER = "admin";
private final String PASS = "123456";
public void authenticate(String user, String pass) {
if (!USER.equals(user)) {
throw new InvalidCredentialException("用户名错误");
}
if (!PASS.equals(pass)) {
throw new InvalidCredentialException("密码错误");
}
System.out.println("登录成功");
}
public static void main(String[] args) {
AuthService service = new AuthService();
try {
service.authenticate("admin", "123456");
} catch (InvalidCredentialException ex) {
System.out.println(ex.getMessage());
}
}
}
继承Exception默认为受查异常。