Java自定义异常类

Java自定义异常类,java,exception-handling,Java,Exception Handling,我在创建自己的异常类时遇到了一个相当小的问题。我对它进行了扩展,并试图在构造函数中接收一个double,但我不断地得到错误 bankaccount@draw内部错误“不兼容的类型:InsufficientFundsException无法转换为throwable” 例外类别: public class InsufficientFundsException extends RuntimeException { private double shortFall; pu

我在创建自己的异常类时遇到了一个相当小的问题。我对它进行了扩展,并试图在构造函数中接收一个double,但我不断地得到错误

bankaccount@draw内部错误“不兼容的类型: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;   
        }
    }
不过我只有一个构造函数。任何建议或帮助都将不胜感激。

您是否尝试过

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)

您是否有多个名为
InsufficientFundsException
的类?您应该
抛出您创建的新异常。我已经抛出了,但我只是再次尝试验证,我得到了“类中的构造函数InsufficientFundsException InsufficientFundsException InsufficientFundsException无法应用于给定类型”刚刚添加了我的代码更改。我得到了预期的例外。谢谢shrirrine,但我仍然有一个问题。我在想也许我声明的实际异常类是错误的?方法签名中当前的错误是不兼容的类型:InsufficientFundsException无法转换为Throwable。原始帖子中的异常类声明没有问题。这就是我在Eclipse中运行的。这可能与。。。我在Netbeans中重新编译的代码现在似乎可以工作了。看起来这是一个等级问题。谢谢你的时间,雪琳!