有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我无法让我的用户定义检查异常正常工作

我需要创建一个用户定义的已检查异常。不幸的是,当我试图抛出它时,我得到了一个错误:未报告的异常资金不足;必须被抓住或宣布被抛出

我已经在方法签名中识别了异常,然后在我希望发生异常的方法中抛出异常。然而,我仍然无法理解我所犯的错误

如有任何意见,将不胜感激

代码示例: main()

if (e.getSource() == deposit) {
    accountType.deposit(money);
} else if (e.getSource() == withdraw) {
    if (money % 20 == 0) {
        accountType.withdraw(money);
    } else {
        JOptionPane.showMessageDialog(null, "Entry must be in $20 increments.");
    }
}

在本例中,我在“accountType.deposit(money);”处收到未报告的异常错误它运行以下方法:

public void withdraw(Double money) throws InsufficientFunds {
    if (count >= 4) {
        this.money = (money + FEE);
    } else {
        this.money = money;
    }
    if (this.balance < this.money) {
        throw new InsufficientFunds("You don't have enough money to do that!");
    } else {
        this.balance -= this.money;
        count++;    
    }
}

这是我的用户定义的异常类

public class InsufficientFunds extends Exception {

    public InsufficientFunds(String s) {
        super(s);
    }
}

任何人都可以把这方面的眼睛,并提供一些知识,我将不胜感激。我肯定我忽略了一些简单的事情

谢谢,, 布莱恩


共 (2) 个答案

  1. # 1 楼答案

    withdraw()方法中抛出一个名为InsufficientFunds的自定义异常,但在调用方法中从未捕获该异常。因此,消除错误的一种方法是将对withdraw()的调用放在try-catch块中:

    if (e.getSource() == deposit) {
        accountType.deposit(money);
    } else if (e.getSource() == withdraw) {
        if (money % 20 == 0) {
            try {
                accountType.withdraw(money);
            }
            catch (InsufficientFunds ife) {
                System.out.println("No funds to withdraw.");
            }
            catch (Exception e) {
                System.out.println("Some other error occurred.");
            }
        } else {
            JOptionPane.showMessageDialog(null, "Entry must be in $20 increments.");
        }
    }
    

    如果你仔细观察,你会发现我首先捕获了一个InsufficientFunds异常,然后是一个常规的Exception。这是您通常想要遵循的模式,即先捕获特定的异常,再捕获更一般的异常,最后捕获Exception,以确保您处理每个可能出错的用例

    另一种选择是让调用withdraw()to的方法也抛出异常,即

    public static void main(String[] args) throws InsufficientFunds {
        if (e.getSource() == deposit) {
            accountType.deposit(money);
        } else if (e.getSource() == withdraw) {
            if (money % 20 == 0) {
                accountType.withdraw(money);
            } else {
                JOptionPane.showMessageDialog(null, "Entry must be in $20 increments.");
            }
        }
    }
    
  2. # 2 楼答案

    您正在抛出自定义异常,但它从未在withdraw()中被捕获。Java使用Catch或Declare规则,这意味着必须在catch块中捕获异常,或者在方法标题中用throws关键字声明异常

    有关更多详细信息,请参见this reference