MrGamma195
MrGamma195

Reputation: 35

Java Assertion Exception

I've made s simple program to let the user withdraw a certain amount out of a bank account, and if they withdraw too much it will cause an AssertionError, how do I get it to write out the error?

import java.util.Scanner;

public class Withdraw {

    public static void main(String[]args){
        Scanner a = new Scanner(System.in);

        int t = 10000;
        System.out.println("Withdraw or Deposit");
        String in = a.next();
        System.out.println("Enter your value");
        int wd = a.nextInt();

        if(in.equals("withdraw")){
            int b;
            b = t - wd;
            System.out.println(t);
            if (b < 0){
                throw new AssertionError();
            }
        }
    }

}

Upvotes: 0

Views: 4019

Answers (2)

Yudhister Satija
Yudhister Satija

Reputation: 33

Replace the if block containing throw with:

assert b>0 : "Invalid Assertion, b must be positive"

The String message can be whatever you want. But this is only useful if you run your program as

java -ea ClassName

If you want to throw error in normal java runtime environment, don't use AssertionError. It is meant for the assert statement. Throw a custom exception, or use some exception class's Exception(String message) constructor.

Upvotes: 0

Hamy
Hamy

Reputation: 21602

I'll assume you want your AssertionError to include some information on the balance. You're using the constructor AssertionError(). According to the documentation, you can also use the constructor AssertionError(Object detailMessage) where the object will be converted to a string. So you can do this:

throw new AssertionError("Oh no, your balance " + b + " is negative!");

PS - Your two if statements have different spacing e.g. if( versus if (. This is an example of "code smell" - not a true error, but poor style indicating carelessness. Try to keep these little things consistent going forward and your code will look cleaner and more readable

Upvotes: 1

Related Questions