2015-02-17 116 views
1

我在创建自己的异常类时遇到了一个相当微不足道的问题。我已经扩展它,并试图在构造函数中接受一个double,但我不断收到错误。Java自定义异常类

的BankAccount @withdraw内部错误 “不兼容的类型:InsufficientFundsException不能转换到抛出”

Exception类:

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; 
     } 
    } 

我想除非提款超过目前的余额,否则取款。在这种情况下,我想抛出一个异常。我也尝试抛出和例外,但如果我得到:

构造函数InsufficientFundsException类InsufficientFundsException不能应用于gived类型; 要求:无参数 发现:双 原因:实际的和正式的参数列表长度

public void withdraw(double w) { 

     double difference; 
     if(w > balance) { 
      difference = w - balance; 
      Exception ex = new InsufficientFundsException(difference); 
     } else { 
      balance -= w; 
     } 
    } 

不同我只有一个构造函数,虽然。任何意见或帮助表示赞赏。

+0

你有所谓的多个类'InsufficientFundsException '? – immibis 2015-02-17 23:48:19

+0

你应该抛出你创建的新异常。 – rgettman 2015-02-17 23:49:08

回答

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); 
} 

了....

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) 
+0

我有但我只是再次尝试验证我得到“构造函数InsufficientFundsException在类InsufficientFundsException不能应用于给定的类型” – eip56 2015-02-18 00:20:47

+0

刚刚添加我的代码更改。我得到了预期的例外。 – shirrine 2015-02-18 00:33:34

+0

谢谢你的疱疹,但我仍然有一个问题。我想也许我宣布实际的异常类错了?目前在方法签名中的错误是不兼容的类型:InsufficientFundsException不能转换为Throwable。 – eip56 2015-02-18 00:39:46