在Java Error中抛出多个异常

时间:2013-07-16 03:39:36

标签: java object exception-handling try-catch

错误:未报告的异常NotEnoughBalance;必须被抓住或宣布被抛出

错误:未报告的异常NegativeWithdraw;必须被抓住或宣布被抛出

基本上,我不确定如何报告我的异常,因为我抛出它们并在满足条件时创建新的异常。我的问题主要是因为我在同一个方法中放了两个catch异常,只使用一个异常就不会产生错误。

这些是在我的对象类

中共享方法的try demo语句
try {
    account.withdraw(passNegative);
}
catch(NegativeWithdraw e) {
    System.out.println(e.getMessage());
}

代码的不同部分

try {
    account.withdraw(1);
}
catch(NotEnoughBalance e) {
    System.out.println(e.getMessage());
}

当程序捕获两个异常时,我在这里定义输出:

public class NegativeWithdraw extends Exception {
    // This constructor uses a generic error message.
    public NegativeWithdraw() {
        super("Error: Negative withdraw");
    }
   // This constructor specifies the bad starting balance in the error message.
   public NegativeWithdraw(double amount) {
        super("Error: Negative withdraw: " + amount);
    }
}

不同的程序

public class NotEnoughBalance extends Exception {
    // This constructor uses a generic error message.
    public NotEnoughBalance() {
        super("Error: You don't have enough money in your bank account to withdraw that much");
    }

    // This constructor specifies the bad starting balance in the error message.
    public NotEnoughBalance(double amount) {
        super("Error: You don't have enough money in your bank account to withdraw $" + amount + ".");
    }
}

这是我的对象类,它编译得很好,但我认为是我的程序所在的位置。我在网上查找了如何在一个方法中保存多个异常,并发现你在抛出异常之间使用了一个共同点,但对于我做错了什么仍然有点困惑。

public class BankAccount {
    private double balance; // Account balance

    // This constructor sets the starting balance at 0.0.
    public BankAccount() {
        balance = 0.0;
    }

    // The withdraw method withdraws an amount from the account.
    public void withdraw(double amount) throws NegativeWithdraw, NotEnoughBalance {
        if (amount < 0)
            throw new NegativeWithdraw(amount);
        else if (amount > balance)
            throw new NotEnoughBalance(amount);
        balance -= amount;
    }

    //set and get methods (not that important to code, but may be required to run)
    public void setBalance(String str) {
        balance = Double.parseDouble(str);
    }

    // The getBalance method returns the account balance.
    public double getBalance() {
        return balance;
    }
}

1 个答案:

答案 0 :(得分:3)

每当你调用account.withdraw函数时,你需要捕获两个异常,因为你不知道会抛出哪一个(你可能知道,但编译器没有)

例如

try {
     account.withdraw(passNegative);
}
catch(NegativeWithdraw | NotEnoughBalance e) {
    System.out.println(e.getMessage());
}

编辑: 正如另一个用户所指出的,这是针对Java 7的

对于旧版本,您可以做很多事情

try {
    account.withdraw(passNegative);
} catch(NegativeWithdraw e) {
    System.out.println(e.getMessage());
} catch(NotEnoughBalance e) {
    System.out.println(e.getMessage());
}