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来阻止程序崩溃,但仍然打印出错误,谢谢
答案 0 :(得分:2)
您应该使用try catch包装引发错误的方法,像这样
// ... some code
try {
payForMeal(amount);
} catch (ArithmeticException e) {
System.out.log("An error occurred trying to pay for the meal: " + e.getMessage());
}
// ... more code
如何处理错误由您决定。
答案 1 :(得分:1)
尝试减少您的方法。编程是关于问题分解和设计的。
具有一个checkBalanceSufficient
方法,该方法返回结果,而不是在您的代码中执行此操作。检查它需要返回什么样的数据。不要输入任何打印语句,这是针对您的主要方法或与UI相关的类和方法的。
请勿重复使用ArithmeticException
。计算很好,这是您不满意的<结果>结果。因此,您需要定义自己的更高级别的异常(对异常进行编程非常容易,只需扩展Exception
)。最好您的代码永远不会由于输入问题而引发异常;您可以在代码的早期用单独的方法处理错误的输入。
如果catch
子句中有任何更高级别的代码(即实现用例的代码),则说明您已经做错了。