我需要创建一个用户定义的检查异常。不幸的是,当我尝试抛出它时,我收到错误:未报告的异常 InsufficientFunds;必须被捕获或宣布被抛出。
我已经在方法签名中识别出异常,然后将其抛出到我希望发生的方法中。但是,我仍然无法理解我所犯的错误。
任何意见都将不胜感激。
代码示例: main()
if (e.getSource() == deposit) {
accountType.deposit(money);
} else if (e.getSource() == withdraw) {
if (money % 20 == 0) {
accountType.withdraw(money);
} else {
JOptionPane.showMessageDialog(null, "Entry must be in $20 increments.");
}
}
在此示例中,我在“accountType.deposit(money);”处收到未报告的异常错误它运行以下方法:
public void withdraw(Double money) throws InsufficientFunds {
if (count >= 4) {
this.money = (money + FEE);
} else {
this.money = money;
}
if (this.balance < this.money) {
throw new InsufficientFunds("You don't have enough money to do that!");
} else {
this.balance -= this.money;
count++;
}
}
这是我的用户定义的异常类
public class InsufficientFunds extends Exception {
public InsufficientFunds(String s) {
super(s);
}
}
任何能够关注这一点并为我提供一些知识的人将不胜感激。我确信我忽略了一些事情。
谢谢你, 布莱恩
最佳答案
您在 withdraw()
方法中抛出了一个名为 InsufficientFunds
的自定义异常,但您从未在调用方法中捕获该异常。因此,消除错误的一种方法是将对 withdraw()
的调用置于 try-catch
block 内:
if (e.getSource() == deposit) {
accountType.deposit(money);
} else if (e.getSource() == withdraw) {
if (money % 20 == 0) {
try {
accountType.withdraw(money);
}
catch (InsufficientFunds ife) {
System.out.println("No funds to withdraw.");
}
catch (Exception e) {
System.out.println("Some other error occurred.");
}
} else {
JOptionPane.showMessageDialog(null, "Entry must be in $20 increments.");
}
}
如果仔细观察,您会发现我首先捕获 InsufficientFunds
异常,然后捕获一般 Exception
。这是您通常想要遵循的模式,即捕获特定的异常,然后捕获更一般的异常,最后捕获Exception
以确保您处理每个可能出错的用例。
另一种方法是让调用 withdraw()
的方法也抛出异常,即
public static void main(String[] args) throws InsufficientFunds {
if (e.getSource() == deposit) {
accountType.deposit(money);
} else if (e.getSource() == withdraw) {
if (money % 20 == 0) {
accountType.withdraw(money);
} else {
JOptionPane.showMessageDialog(null, "Entry must be in $20 increments.");
}
}
}
关于java - 我无法让用户定义的检查异常正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780941/