throw关键字
throw用于在代码中手动抛出异常对象。
基本语法
抛出异常对象
throw后跟异常对象实例,立即中断当前执行流程。
Java
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
if (age > 150) {
throw new IllegalArgumentException("年龄超出范围");
}
this.age = age;
}
抛出异常流程
Java
public void process(String str) {
if (str == null) {
throw new NullPointerException("参数不能为空");
}
// throw后代码不执行
System.out.println(str); // 不执行
}
throw作用
主动触发异常
程序逻辑判断后主动抛出异常。
Java
public void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("取款金额必须大于0");
}
if (amount > balance) {
throw new IllegalStateException("余额不足");
}
balance -= amount;
}
参数校验
Java
public void setName(String name) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("姓名不能为空");
}
if (name.length() > 20) {
throw new IllegalArgumentException("姓名长度不能超过20");
}
this.name = name;
}
创建异常对象
使用现有异常类
Java
// 使用Java内置异常类
throw new NullPointerException();
throw new IllegalArgumentException("参数错误");
throw new IllegalStateException("状态错误");
throw new ArithmeticException("算术错误");
常用内置异常类
| 异常类 | 适用场景 |
|---|---|
| IllegalArgumentException | 参数不合法 |
| NullPointerException | 空指针 |
| IllegalStateException | 状态不合法 |
| UnsupportedOperationException | 不支持的操作 |
| IndexOutOfBoundsException | 索引越界 |
| ArithmeticException | 算术错误 |
自定义异常消息
Java
throw new IllegalArgumentException("用户ID不能为空");
throw new IllegalStateException("订单状态不允许取消");
// 获取消息
try {
// ...
} catch (IllegalArgumentException e) {
String msg = e.getMessage(); // "用户ID不能为空"
}
throw与throws配合
throw后需要throws声明
方法内throw检查型异常,方法签名需throws声明。
Java
// 检查型异常:需要throws
public void readFile() throws IOException {
if (!file.exists()) {
throw new IOException("文件不存在");
}
}
// 非检查型异常:不需要throws(可选)
public void check(String str) {
if (str == null) {
throw new NullPointerException("参数为空");
}
}
检查型异常必须处理
Java
public void method() throws IOException {
throw new IOException("IO错误"); // 检查型异常,需要throws
}
// 调用者处理
public void caller() {
try {
method();
} catch (IOException e) {
e.printStackTrace();
}
}
抛出异常后流程
立即中断执行
throw语句执行后,当前方法立即返回,异常向上传播。
Java
public void test() {
System.out.println("开始");
throw new RuntimeException("中断");
System.out.println("结束"); // 不执行
}
异常传播
异常沿调用链向上查找匹配的catch块。
Java
public void methodA() {
try {
methodB();
} catch (RuntimeException e) {
System.out.println("捕获异常"); // 捕获methodB抛出的异常
}
}
public void methodB() {
methodC();
}
public void methodC() {
throw new RuntimeException("异常源头"); // 抛出点
}
使用场景
参数校验
Java
public void setId(Long id) {
if (id == null) {
throw new IllegalArgumentException("ID不能为空");
}
if (id <= 0) {
throw new IllegalArgumentException("ID必须大于0");
}
this.id = id;
}
业务规则检查
Java
public void transfer(Account from, Account to, double amount) {
if (from.getBalance() < amount) {
throw new IllegalStateException("转出账户余额不足");
}
if (to == null) {
throw new IllegalArgumentException("转入账户不存在");
}
// 执行转账
}
状态检查
Java
public void cancelOrder(Order order) {
if (order.getStatus() == Status.COMPLETED) {
throw new IllegalStateException("已完成订单不能取消");
}
order.setStatus(Status.CANCELLED);
}
throw与throws对比
核心区别
| 特性 | throw | throws |
|---|---|---|
| 位置 | 方法体内 | 方法签名 |
| 作用 | 抛出异常对象 | 声明异常类型 |
| 后跟内容 | 异常对象实例 | 异常类型列表 |
| 执行效果 | 立即中断 | 声明可能抛出 |
配合使用
Java
// throw在方法内,throws在签名
public void validate(String input) throws IllegalArgumentException {
if (input == null) {
throw new IllegalArgumentException("输入不能为空");
}
}
要点总结
- throw手动抛出异常对象
- throw后跟异常实例(new Exception)
- throw立即中断当前执行流程
- 常用于参数校验、业务规则检查
- 检查型异常throw后需要throws声明
- 非检查型异常throw无需throws(可选)
- throw在方法体内,throws在方法签名
- 常用IllegalArgumentException表示参数错误
- 常用IllegalStateException表示状态错误
- 异常沿调用链向上传播直到被捕获
📝 发现内容有误?点击此处直接编辑