在如下Java代码片段中,`Bank`类定义了`deposit`和`withdraw`方法,其中`withdraw`方法可能会抛出自定义异常`BankException`。在`operate`方法中,如果先执行两次`deposit`操作,再执行两次`withdraw`操作,若初始账户余额为0,且两次`withdraw`操作分别尝试取款500和1000,则程序运行的结果会是什么? ```java class BankException extends Exception { public BankException(String message) { super(message); } } class Bank { private double balance; public Bank(double initialBalance) { this.balance = initialBalance; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public void deposit(double amount) { this.setBalance(this.getBalance() + amount); System.out.println("存款金额:"+amount+",现有余额:"+this.getBalance()); } public double withdraw(double amount) throws BankException { if (amount <= this.getBalance()) { this.setBalance(this.getBalance() - amount); System.out.println("取款金额:" + amount + ",现有余额:" + this.getBalance()); } else { BankException be = new BankException("余额不足,操作失败!"); throw be; } return this.getBalance(); } } public class Main { public static void main(String[] args) { try { operate(); } catch (BankException e) { System.err.println(e.getMessage()); } } public static void operate() throws BankException { Bank bank = new Bank(0); bank.deposit(300); bank.deposit(500); bank.withdraw(500); bank.withdraw(1000); System.out.println("任务完成!"); } } ```
答案解析
程序首先进行两次存款操作,余额分别为300和800。第一次取款500成功,余额变为300。第二次取款尝试取款1000,此时余额不足,`withdraw`方法会抛出`BankException`异常。这个异常在`main`方法的`try-catch`块中被捕获,并打印错误信息到错误流中。由于异常抛出后,`operate`方法中的后续代码不再执行,因此不会打印“任务完成!”。选项A错误,因为它忽略了异常的抛出;选项C错误,它忽略了第一次取款成功。选项D错误,它认为“任务完成!”被打印。
正确答案:B