在java中,受检自定义异常通过继承 exception 类来创建,并在方法签名中使用 throws 关键字声明,强制调用方进行显式处理。具体做法是定义一个类继承 exception,然后在抛出该异常的方法上添加 throws 子句,调用者必须使用 try-catch 块捕获或继续向上抛出,否则代码无法编译。

如何定义并声明一个受检自定义异常
要创建一个受检异常,只需让新类继承 java.lang.Exception 而非 RuntimeException。接着在业务方法签名中加入 throws 声明,编译器会据此检查调用链。例如定义 InsufficientFundsException 并在取款方法中抛出,调用者若不捕获则编译报错。

public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// 声明抛出受检异常
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("余额不足: " + amount);
}
balance -= amount;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(100.0);
try {
account.withdraw(150.0);
} catch (InsufficientFundsException e) {
System.out.println("捕获异常: " + e.getMessage());
}
}
}调用方如何处理受检异常
当方法声明了受检异常时,调用方有两种选择:要么用 try-catch 捕获并处理,要么在自身方法签名中继续 throws。若选择捕获,通常结合日志记录或用户提示;若选择继续抛出,异常将沿调用栈向上传递直到被处理或终止程序。这种机制确保关键错误不会静默丢失。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
立即学习“Java免费学习笔记(深入)”;

// 调用方处理方式1:捕获并处理
public void processTransaction() {
BankAccount account = new BankAccount(100.0);
try {
account.withdraw(150.0);
} catch (InsufficientFundsException e) {
// 处理逻辑,如记录日志或返回错误码
System.err.println("交易失败: " + e.getMessage());
}
}
// 调用方处理方式2:继续抛出
public void riskyOperation() throws InsufficientFundsException {
BankAccount account = new BankAccount(100.0);
account.withdraw(150.0); // 编译器要求此处处理或声明throws
}当余额为负数时异常的具体行为是什么
在 withdraw 方法中,当传入金额大于当前余额时,条件 amount > balance 成立,程序立即抛出 InsufficientFundsException 实例。此时 balance 不会被修改,因为抛出语句位于余额扣减之前。调用方若未捕获,JVM 将打印堆栈跟踪并终止线程;若已捕获,则执行 catch 块中的逻辑,异常对象包含构造时传入的消息字符串。

















