0

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

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

基本上,我不确定当我抛出异常并在满足条件时创建一个新异常时如何不报告我的异常。我的问题主要涉及这样一个事实,即我将两个 catch 异常放在同一个方法中,只使用一个异常不会产生错误。

这些是在我的对象类中共享一个方法的尝试演示语句

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

1 回答 1

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());
}
于 2013-07-16T03:51:24.327 回答