【问题标题】:Try-Catch statement JavaTry-Catch 语句 Java
【发布时间】:2019-11-19 15:58:18
【问题描述】:
public void payForMeal(double amount) throws Exception {
    if (balance - amount < 0 && amount - balance <= creditLimit) {
        this.strStatus = "Using Credit";
        double newBalance = balance - amount;
        balance = newBalance;

        throw new ArithmeticException("\n\n-----------------------------\n" + "You must top-up your balance\n" + "Your new balance is: " + balance + "\n" + "You are: " + strStatus + "\n" + "-----------------------------\n");
    }//if

    else if (amount > creditLimit && balance < amount) {
        throw new ArithmeticException("\n\n----------------------\n" + "Cost of meal exceeds the credit limit." + "\n----------------------\n");

    }//elseif
    else {
        double newBalance = balance - amount;
        balance = newBalance;
        transCount++;
    }//else  
}//payForMeal

当余额为 2 且 payForMeal 设置为 8 时,程序崩溃前会打印以下内容:

显示帐户详细信息:

餐费超出信用额度。

Customer ID:       200
Name:              Joe
Balance:           2.0
Minimum TopUp:     2.0
Account Status:    Valid
Credit Limit:      5.0
Transaction Count: 0

如何添加一个 try-catch 来阻止程序崩溃但仍然打印出错误,谢谢

【问题讨论】:

  • 如果你清理了缩进,你对自己代码的理解会大大提高。

标签: java exception try-catch


【解决方案1】:

你应该用 try catch 包裹抛出错误的方法,像这样

// ... some code

try {
  payForMeal(amount);
} catch (ArithmeticException e) {
  System.out.log("An error occurred trying to pay for the meal: " + e.getMessage());
}

// ... more code

如何处理错误由您决定。

【讨论】:

  • 正如my answer 中解释的那样,代码可以运行,但是它将编程问题变成了程序设计问题。
【解决方案2】:

尽量少用你的方法。编程是关于问题的分解和设计。

有一个checkBalanceSufficient 方法返回一个结果,而不是在你的代码中这样做。检查它需要返回什么样的数据。不要放入任何打印语句,这是针对您的主要方法或与 UI 相关的类和方法的。

不要重复使用ArithmeticException。计算很好,是你不满意的结果。所以你需要定义你自己的更高级别的异常(编写异常真的很容易,只需扩展Exception)。最好你的代码永远不会因为输入问题而抛出异常;您可以在代码的早期在单独的方法中处理错误的输入。

如果在catch 子句中有任何更高级别的代码(即实现用例的代码),那么你已经做错了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    相关资源
    最近更新 更多