简化Java异常处理:实战示例

原创 小咪咪 2024-11-28 06:21 71阅读 0赞

Java异常处理是编写健壮代码的关键部分。以下是一个简单且实用的Java异常处理示例:

  1. public class BankAccount {
  2. private double balance;
  3. // 构造函数,初始化账户余额
  4. public BankAccount(double initialBalance) {
  5. if (initialBalance < 0) { // 检查输入是否合理
  6. throw new IllegalArgumentException("Initial balance cannot be negative.");
  7. }
  8. this.balance = initialBalance;
  9. }
  10. // 提供一个方法来增加账户余额
  11. public void deposit(double amount) {
  12. if (amount <= 0) { // 再次检查输入是否合理
  13. throw new IllegalArgumentException("Deposit amount must be positive.");
  14. }
  15. balance += amount;
  16. System.out.println("Account balance updated to: " + balance);
  17. }
  18. // 提供一个方法来减少账户余额
  19. public void withdraw(double amount) {
  20. if (amount <= 0 || amount > balance) { // 再次检查输入是否合理以及账户余额是否足够
  21. throw new IllegalArgumentException("Withdrawal amount must be positive and less than or equal to current balance.");
  22. }
  23. balance -= amount;
  24. System.out.println("Account balance updated to: " + balance);
  25. }
  26. // 主函数,演示如何使用异常处理
  27. public static void main(String[] args) {
  28. BankAccount account = new BankAccount(100); // 创建一个初始余额为100的账户
  29. try { // 异常处理开始
  30. account.deposit(50); // 向账户存款50元
  31. account.withdraw(20); // 从账户中取出20元
  32. } catch (IllegalArgumentException e) { // 检查是否抛出异常
  33. System.out.println("Error: " + e.getMessage()); // 输出错误信息
  34. } finally {
  35. System.out.println("Account balance after operations: " + account.balance);
  36. }
  37. }
  38. }

这个示例展示了如何在Java中使用try-catch语句来捕获和处理可能出现的异常。

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

发表评论

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

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

相关阅读