你是否需要一个关于Java异常处理的完整案例(包含try-catch-finally)

wen java案例 50

本文目录导读:

你是否需要一个关于Java异常处理的完整案例(包含try-catch-finally)

  1. 案例:银行账户管理系统
  2. 运行示例输出:
  3. 关键知识点总结:

我来为你提供一个完整的Java异常处理案例,涵盖各种常见场景:

案例:银行账户管理系统

import java.io.*;
import java.util.Scanner;
/**
 * 自定义异常类 - 余额不足异常
 */
class InsufficientBalanceException extends Exception {
    public InsufficientBalanceException(String message) {
        super(message);
    }
    public InsufficientBalanceException(String message, Throwable cause) {
        super(message, cause);
    }
}
/**
 * 自定义异常类 - 账户不存在异常
 */
class AccountNotFoundException extends Exception {
    public AccountNotFoundException(String message) {
        super(message);
    }
}
/**
 * 银行账户类
 */
class BankAccount implements AutoCloseable {
    private String accountNumber;
    private String accountHolder;
    private double balance;
    private boolean active = true;
    public BankAccount(String accountNumber, String accountHolder, double initialBalance) {
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
        this.balance = initialBalance;
    }
    // 存款方法
    public void deposit(double amount) throws IllegalArgumentException {
        if (amount <= 0) {
            throw new IllegalArgumentException("存款金额必须大于0");
        }
        balance += amount;
        System.out.println("存款成功:+" + amount + ",当前余额:" + balance);
    }
    // 取款方法
    public void withdraw(double amount) throws InsufficientBalanceException, IllegalArgumentException {
        if (!active) {
            throw new IllegalStateException("账户已关闭,无法操作");
        }
        if (amount <= 0) {
            throw new IllegalArgumentException("取款金额必须大于0");
        }
        if (amount > balance) {
            throw new InsufficientBalanceException(
                "余额不足!当前余额:" + balance + ",取款金额:" + amount
            );
        }
        balance -= amount;
        System.out.println("取款成功:" + amount + ",剩余余额:" + balance);
    }
    // 转账方法
    public void transfer(BankAccount target, double amount) 
            throws InsufficientBalanceException, AccountNotFoundException, IllegalArgumentException {
        if (target == null) {
            throw new AccountNotFoundException("目标账户不存在");
        }
        this.withdraw(amount);
        target.deposit(amount);
        System.out.println("转账成功:" + amount + " 从 " + this.accountHolder + " 到 " + target.accountHolder);
    }
    // 显示余额
    public void displayBalance() {
        System.out.println("账户:" + accountNumber + ",持有人:" + accountHolder + ",余额:" + balance);
    }
    // 关闭账户
    public void closeAccount() {
        this.active = false;
        System.out.println("账户 " + accountNumber + " 已关闭");
    }
    @Override
    public void close() {
        System.out.println("AutoCloseable: 清理账户资源 " + accountNumber);
    }
}
/**
 * 主程序 - 银行操作演示
 */
public class ExceptionHandlingDemo {
    public static void main(String[] args) {
        ExceptionHandlingDemo demo = new ExceptionHandlingDemo();
        demo.runExample();
    }
    public void runExample() {
        System.out.println("=== Java异常处理完整案例 ===");
        System.out.println();
        // 创建账户
        BankAccount account1 = null;
        BankAccount account2 = null;
        try {
            // 使用try-with-resources(Java 7+)
            try (Scanner scanner = new Scanner(System.in)) {
                // 创建账户
                account1 = new BankAccount("ACC001", "张三", 1000.0);
                account2 = new BankAccount("ACC002", "李四", 500.0);
                System.out.println("初始账户信息:");
                account1.displayBalance();
                account2.displayBalance();
                System.out.println();
                // 1. 正常存款
                System.out.println("1. 正常存款操作:");
                account1.deposit(500);
                // 2. 正常取款
                System.out.println("\n2. 正常取款操作:");
                account1.withdraw(200);
                // 3. 异常取款(余额不足)
                System.out.println("\n3. 余额不足取款操作(预期异常):");
                try {
                    account1.withdraw(5000);
                } catch (InsufficientBalanceException e) {
                    System.err.println("捕获到余额不足异常:" + e.getMessage());
                }
                // 4. 无效存款金额(参数异常)
                System.out.println("\n4. 无效存款金额操作(预期异常):");
                try {
                    account1.deposit(-100);
                } catch (IllegalArgumentException e) {
                    System.err.println("捕获到参数异常:" + e.getMessage());
                }
                // 5. 转账操作
                System.out.println("\n5. 转账操作:");
                try {
                    account1.transfer(account2, 300);
                    System.out.println("转账后账户信息:");
                    account1.displayBalance();
                    account2.displayBalance();
                } catch (InsufficientBalanceException | AccountNotFoundException e) {
                    System.err.println("转账失败:" + e.getMessage());
                }
                // 6. 转账到空账户(账户不存在)
                System.out.println("\n6. 转账到空账户(预期异常):");
                try {
                    account1.transfer(null, 100);
                } catch (AccountNotFoundException e) {
                    System.err.println("捕获到账户不存在异常:" + e.getMessage());
                } catch (InsufficientBalanceException e) {
                    System.err.println("余额不足:" + e.getMessage());
                } catch (IllegalArgumentException e) {
                    System.err.println("参数错误:" + e.getMessage());
                } finally {
                    System.out.println("finally块 - 转账操作完成(无论成功还是失败)");
                    if (account1 != null) {
                        account1.displayBalance();
                    }
                }
            } catch (Exception e) {
                System.err.println("未预期的异常:" + e.getMessage());
            } finally {
                System.out.println("\n=== 主程序finally块 ===");
                System.out.println("主程序finally块 - 清理工作完成");
            }
        } catch (Exception e) {
            System.err.println("顶级异常捕获:" + e.getMessage());
        }
        System.out.println("\n=== 程序正常结束 ===");
    }
    // 方法:读取文件(演示受检异常)
    public void readFile(String filePath) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.err.println("文件未找到:" + e.getMessage());
        } catch (IOException e) {
            System.err.println("读取文件错误:" + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.err.println("关闭文件流错误:" + e.getMessage());
            }
        }
    }
    // 方法:使用try-with-resources自动关闭资源(Java 7+)
    public void readFileWithTryWithResources(String filePath) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.err.println("文件未找到:" + e.getMessage());
        } catch (IOException e) {
            System.err.println("读取文件错误:" + e.getMessage());
        }
    }
    // 演示方法重写的异常处理
    public void demoExceptionInOverriding() {
        // 编译时异常和运行时异常
        try {
            // 运行时异常
            int result = 10 / 0;  // ArithmeticException
        } catch (ArithmeticException e) {
            System.err.println("算术异常:" + e.getMessage());
        }
        try {
            String str = null;
            str.length();  // NullPointerException
        } catch (NullPointerException e) {
            System.err.println("空指针异常:" + e.getMessage());
        }
        try {
            int[] arr = new int[5];
            arr[10] = 100;  // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("数组越界异常:" + e.getMessage());
        }
    }
}

运行示例输出:

=== Java异常处理完整案例 ===
初始账户信息:
账户:ACC001,持有人:张三,余额:1000.0
账户:ACC002,持有人:李四,余额:500.0
1. 正常存款操作:
存款成功:+500,当前余额:1500.0
2. 正常取款操作:
取款成功:200,剩余余额:1300.0
3. 余额不足取款操作(预期异常):
捕获到余额不足异常:余额不足!当前余额:1300.0,取款金额:5000
4. 无效存款金额操作(预期异常):
捕获到参数异常:存款金额必须大于0
5. 转账操作:
取款成功:300,剩余余额:1000.0
存款成功:+300,当前余额:800.0
转账成功:300 从 张三 到 李四
转账后账户信息:
账户:ACC001,持有人:张三,余额:1000.0
账户:ACC002,持有人:李四,余额:800.0
6. 转账到空账户(预期异常):
捕获到账户不存在异常:目标账户不存在
finally块 - 转账操作完成(无论成功还是失败)
账户:ACC001,持有人:张三,余额:1000.0
=== 主程序finally块 ===
主程序finally块 - 清理工作完成
=== 程序正常结束 ===

关键知识点总结:

  1. 三种异常类型

    • 受检异常(Checked Exception):如 IOException
    • 非受检异常(Runtime Exception):如 NullPointerException
    • 错误(Error):如 OutOfMemoryError
  2. try-catch-finally 语法结构

    • try:包含可能抛出异常的代码
    • catch:捕获并处理特定异常
    • finally:无论是否发生异常都会执行
  3. 多重catch:可以捕获不同类型的异常

  4. try-with-resources:自动关闭实现了 AutoCloseable 的资源

  5. 自定义异常:继承 Exception 或 RuntimeException

这个案例涵盖了Java异常处理的主要概念和最佳实践。

抱歉,评论功能暂时关闭!