我在创建自己的异常类时遇到了一个相当微不足道的问题。我已经扩展了它,并尝试在构造函数中接收 double 值,但我不断收到错误。
银行帐户@withdraw内部出现错误“不兼容的类型:InsufficientFundsException无法转换为可抛出”
异常类:
public class InsufficientFundsException extends RuntimeException {
private double shortFall;
public InsufficientFundsException(double a) {
super("Insufficient funds");
shortFall = a;
}
public double getAmount() { return shortFall; }
}
银行账户类别:
public class BankAccount {
private int accountNumber;
private double balance;
// Class constructor
public BankAccount(int account) {
accountNumber = account;
balance = 0.0;
}
public int getAccountNumber() {
return accountNumber;
}
public double getBalance()
{
return balance;
}
public void deposit(double b) {
balance += b;
}
public void withdraw(double w) throws InsufficientFundsException {
double difference;
if(w > balance) {
difference = w - balance;
} else {
balance -= w;
}
}
我想提款,除非提款金额大于当前余额。在这种情况下我想抛出异常。我还尝试在 if 内部抛出异常,但我得到:
类 InsufficientFundsException 中的构造函数 InsufficientFundsException 不能应用于给定类型; 必需:无参数 发现:双 原因:实际参数列表和形式参数列表的长度不同
public void withdraw(double w) {
double difference;
if(w > balance) {
difference = w - balance;
Exception ex = new InsufficientFundsException(difference);
} else {
balance -= w;
}
}
不过我只有一个构造函数。如有任何建议或帮助,我们将不胜感激。
最佳答案
你尝试过吗...
throw new InsufficientFundsException(difference);
代替
Exception ex = new InsufficientFundsException(difference);
这通常是抛出异常的方式。
更新了代码片段...
public void withdraw(double w) throws InsufficientFundsException {
double difference;
if(w > balance) {
difference = w - balance;
throw new InsufficientFundsException(difference);
} else {
balance -= w;
}
}
与...一起跑
public static void main(String[] args){
BankAccount account = new BankAccount(1);
account.withdraw(5.0);
}
得到了......
Exception in thread "main" com.misc.help.InsufficientFundsException: Insufficient funds
at com.misc.help.BankAccount.withdraw(BankAccount.java:32)
at com.misc.help.BankAccount.main(BankAccount.java:40)
关于Java自定义异常类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573394/