我在创建自己的异常类时遇到了一个相当小的问题。我已经扩展它,并试图在构造函数中收到一个double,但我一直在收到错误。
bankaccount @withdraw里面的错误“不兼容的类型:InsufficientFundsException无法转换为throwable”
异常类:
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;
}
}
我只有一个构造函数。任何建议或帮助表示赞赏。
答案 0 :(得分:0)
你试过......
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);
}
... GOT
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)