【发布时间】:2019-11-19 15:58:18
【问题描述】:
public void payForMeal(double amount) throws Exception {
if (balance - amount < 0 && amount - balance <= creditLimit) {
this.strStatus = "Using Credit";
double newBalance = balance - amount;
balance = newBalance;
throw new ArithmeticException("\n\n-----------------------------\n" + "You must top-up your balance\n" + "Your new balance is: " + balance + "\n" + "You are: " + strStatus + "\n" + "-----------------------------\n");
}//if
else if (amount > creditLimit && balance < amount) {
throw new ArithmeticException("\n\n----------------------\n" + "Cost of meal exceeds the credit limit." + "\n----------------------\n");
}//elseif
else {
double newBalance = balance - amount;
balance = newBalance;
transCount++;
}//else
}//payForMeal
当余额为 2 且 payForMeal 设置为 8 时,程序崩溃前会打印以下内容:
显示帐户详细信息:
餐费超出信用额度。
Customer ID: 200
Name: Joe
Balance: 2.0
Minimum TopUp: 2.0
Account Status: Valid
Credit Limit: 5.0
Transaction Count: 0
如何添加一个 try-catch 来阻止程序崩溃但仍然打印出错误,谢谢
【问题讨论】:
-
如果你清理了缩进,你对自己代码的理解会大大提高。