[英]Try-Catch statement Java
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 以阻止編程崩潰但仍打印出錯誤,謝謝
您應該使用 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
如何處理錯誤由您決定。
盡量少用你的方法。 編程是關於問題分解和設計的。
有一個checkBalanceSufficient
方法返回一個結果,而不是在你的代碼中這樣做。 檢查它需要返回什么樣的數據。 不要放入任何打印語句,這是針對您的主要方法或與 UI 相關的類和方法的。
不要重用ArithmeticException
。 計算很好,這是您不滿意的結果。 因此,您需要定義自己的更高級別的異常(編寫異常非常容易,只需擴展Exception
)。 最好你的代碼永遠不會因為輸入問題而拋出異常; 您可以在代碼的早期使用單獨的方法處理錯誤輸入。
如果在catch
子句中有任何更高級別的代碼(即實現用例的代碼),那么您已經做錯了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.