Java异常处理不当导致的运行案例
在Java编程中,如果不恰当地进行异常处理,可能会导致程序运行出现各种问题。以下是一个具体的案例:
public class BankAccount {
private double balance;
public void deposit(double amount) throws InsufficientBalanceException {
if (amount < 0) {
throw new IllegalArgumentException("Deposit amount cannot be negative.");
}
balance += amount;
}
public void withdraw(double amount) throws InsufficientBalanceException, InvalidWithdrawalAmountException {
if (amount < 0) {
throw new IllegalArgumentException("Withdrawal amount cannot be negative.");
}
if (amount > balance) {
throw new InvalidWithdrawalAmountException("Insufficient balance for withdrawal amount.");
}
balance -= amount;
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
// 不恰当地处理异常
try {
account.deposit(-10);
} catch (IllegalArgumentException e) {
// 处理异常,如打印错误信息
System.out.println("Error: Deposit amount cannot be negative.");
}
try {
account.withdraw(50);
System.out.println("Withdrawal successful. Balance left: " + account.getBalance());
} catch (InsufficientBalanceException | InvalidWithdrawalAmountException e) {
// 处理异常,如打印错误信息
System.out.println("Error: " + e.getMessage());
}
}
}
在这个案例中,BankAccount
类有存款和取款的方法。当不恰当地处理异常时,可能会导致程序无法正常执行。
例如,在存款-10元的尝试中,没有捕获IllegalArgumentException
,这会导致程序崩溃。在取款50元的尝试中,如果Balance
不足以支付,没有捕获相应的异常,程序也不会给出明确的错误提示。
还没有评论,来说两句吧...