gpt4 book ai didi

java - Java错误中抛出多个异常

转载 作者:行者123 更新时间:2023-12-01 23:42:44 25 4
gpt4 key购买 nike

错误:未报告异常NotEnoughBalance;必须被捕获或宣布被抛出

错误:未报告异常NegativeWithdraw;必须被捕获或宣布被抛出

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

这些是在我的对象类中共享方法的 try 演示语句

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

最佳答案

每次调用 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());
}

关于java - Java错误中抛出多个异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17667616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com