// 自定义检查型异常
public class InvalidAgeException extends Exception {
public InvalidAgeException() {
super();
}
public InvalidAgeException(String message) {
super(message);
}
}
// 自定义非检查型异常
public class BusinessException extends RuntimeException {
public BusinessException(String message) {
super(message);
}
}
(2) 抛出并捕获自定义异常
java
复制
public class UserService {
public void registerUser(int age) throws InvalidAgeException {
if (age < 0) {
throw new InvalidAgeException("年龄不能为负数");
}
// 其他注册逻辑
}
}
// 调用方处理异常
public class Main {
public static void main(String[] args) {
UserService service = new UserService();
try {
service.registerUser(-5);
} catch (InvalidAgeException e) {
System.out.println("注册失败: " + e.getMessage());
}
}
}
三、throws 与 throw
1. 核心区别
关键字
作用
使用场景
throw
手动抛出一个异常对象
在方法内部检测到错误时主动抛出异常
throws
声明方法可能抛出的异常类型
在方法签名中声明异常,由调用者处理
2. 示例
(1) throw 抛出异常
java
复制
public class BankAccount {
private double balance;
public void withdraw(double amount) {
if (amount > balance) {
throw new IllegalArgumentException("余额不足"); // 抛出运行时异常
}
balance -= amount;
}
}
(2) throws 声明异常
java
复制
public class FileProcessor {
public void readFile(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
// 文件操作可能抛出 IOException
}
}
// 调用方必须处理异常
public class Main {
public static void main(String[] args) {
FileProcessor processor = new FileProcessor();
try {
processor.readFile("test.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}