简体   繁体   中英

Try-Catch statement Java

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

when balance is 2 and payForMeal is set to 8 the following prints before the program crashes:

Displaying Account Details:

Cost of meal exceeds the credit limit.

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

How can I add a try-catch to stop the programming from crashing but still print out the errors, thanks

You should wrap the method which throws the error with the try catch, like so

// ... some code

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

// ... more code

How you handle the error is for you to decide.

Try to do less in your methods. Programming is about problem decomposition and design.

Have a checkBalanceSufficient method that returns a result rather than doing this within your code. Check what kind of data it needs to return. Don't put in any print statements, that's for your main method or UI related classes & methods.

Don't reuse ArithmeticException . The calculations are fine, it is the result that you are not happy with. So you need to define your own higher level exception instead (programming an exception is really easy, just extend Exception ). Preferably your code will never throw an exception due to problems with the input though; you can handle bad input within separate methods early in your code.

If there is any higher level code (ie code that implements a use case ) within a catch clause then you are already doing things wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM