[英]Throw multiple exceptions in Java Error
錯誤:未報告的異常NotEnoughBalance; 必須被抓住或宣布被拋出
錯誤:未報告的異常NegativeWithdraw; 必須被抓住或宣布被拋出
基本上,我不確定在拋出異常並在滿足條件時創建新異常時如何不報告異常。 我的問題主要涉及以下事實:我將兩個catch異常放入同一方法中,僅使用一個異常不會產生任何錯誤。
這些是在我的對象類中共享方法的try演示語句
try {
account.withdraw(passNegative);
}
catch(NegativeWithdraw e) {
System.out.println(e.getMessage());
}
代碼的不同部分
try {
account.withdraw(1);
}
catch(NotEnoughBalance e) {
System.out.println(e.getMessage());
}
當程序捕獲到這兩個異常時,我在這里定義輸出:
public class NegativeWithdraw extends Exception {
// This constructor uses a generic error message.
public NegativeWithdraw() {
super("Error: Negative withdraw");
}
// This constructor specifies the bad starting balance in the error message.
public NegativeWithdraw(double amount) {
super("Error: Negative withdraw: " + amount);
}
}
不同的程序
public class NotEnoughBalance extends Exception {
// This constructor uses a generic error message.
public NotEnoughBalance() {
super("Error: You don't have enough money in your bank account to withdraw that much");
}
// This constructor specifies the bad starting balance in the error message.
public NotEnoughBalance(double amount) {
super("Error: You don't have enough money in your bank account to withdraw $" + amount + ".");
}
}
這是我的對象類,可以很好地進行編譯,但是我認為這是我的程序所在的位置。 我在網上尋找如何在一個方法中包含多個異常,並發現在拋出異常之間使用了一個共同點,但是對於我做錯的事情仍然有些困惑。
public class BankAccount {
private double balance; // Account balance
// This constructor sets the starting balance at 0.0.
public BankAccount() {
balance = 0.0;
}
// The withdraw method withdraws an amount from the account.
public void withdraw(double amount) throws NegativeWithdraw, NotEnoughBalance {
if (amount < 0)
throw new NegativeWithdraw(amount);
else if (amount > balance)
throw new NotEnoughBalance(amount);
balance -= amount;
}
//set and get methods (not that important to code, but may be required to run)
public void setBalance(String str) {
balance = Double.parseDouble(str);
}
// The getBalance method returns the account balance.
public double getBalance() {
return balance;
}
}
每次調用account.withdraw函數時,都需要捕獲這兩個異常,因為您不知道將拋出哪個異常(您可能知道,但是編譯器不知道)
例如
try {
account.withdraw(passNegative);
}
catch(NegativeWithdraw | NotEnoughBalance e) {
System.out.println(e.getMessage());
}
編輯:如另一個用戶所述,這是針對Java 7的
對於較舊的版本,您可以做很多事情
try {
account.withdraw(passNegative);
} catch(NegativeWithdraw e) {
System.out.println(e.getMessage());
} catch(NotEnoughBalance e) {
System.out.println(e.getMessage());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.