Java异常处理不当导致的运行案例

原创 亦凉 2024-10-25 04:48 133阅读 0赞

在Java编程中,如果不恰当地进行异常处理,可能会导致程序运行出现各种问题。以下是一个具体的案例:

  1. public class BankAccount {
  2. private double balance;
  3. public void deposit(double amount) throws InsufficientBalanceException {
  4. if (amount < 0) {
  5. throw new IllegalArgumentException("Deposit amount cannot be negative.");
  6. }
  7. balance += amount;
  8. }
  9. public void withdraw(double amount) throws InsufficientBalanceException, InvalidWithdrawalAmountException {
  10. if (amount < 0) {
  11. throw new IllegalArgumentException("Withdrawal amount cannot be negative.");
  12. }
  13. if (amount > balance) {
  14. throw new InvalidWithdrawalAmountException("Insufficient balance for withdrawal amount.");
  15. }
  16. balance -= amount;
  17. }
  18. public double getBalance() {
  19. return balance;
  20. }
  21. }
  22. public class Main {
  23. public static void main(String[] args) {
  24. BankAccount account = new BankAccount();
  25. // 不恰当地处理异常
  26. try {
  27. account.deposit(-10);
  28. } catch (IllegalArgumentException e) {
  29. // 处理异常,如打印错误信息
  30. System.out.println("Error: Deposit amount cannot be negative.");
  31. }
  32. try {
  33. account.withdraw(50);
  34. System.out.println("Withdrawal successful. Balance left: " + account.getBalance());
  35. } catch (InsufficientBalanceException | InvalidWithdrawalAmountException e) {
  36. // 处理异常,如打印错误信息
  37. System.out.println("Error: " + e.getMessage());
  38. }
  39. }
  40. }

在这个案例中,BankAccount类有存款和取款的方法。当不恰当地处理异常时,可能会导致程序无法正常执行。

例如,在存款-10元的尝试中,没有捕获IllegalArgumentException,这会导致程序崩溃。在取款50元的尝试中,如果Balance不足以支付,没有捕获相应的异常,程序也不会给出明确的错误提示。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,133人围观)

还没有评论,来说两句吧...

相关阅读