Try and Catch does not work with assert keyword | Core Java Forum
V
Vikrant Posted on 21/07/2021

Hi Yogesh,

I was doing the practise for the assertion exception at my end. So I have written few statements or lines or codes below to assert keyword. 

So due to that its preventing to executing the further execution due to I got an error using assert keyword. So I thought to cover asstert keyword line in try block but it does not work.

Can you guide me where can we do the same or not.


M
Replied on 21/07/2021

Assertion is not there to indicate that something went wrong in the course of executing your program, but to indicate that your assumptions about your code is wrong.

When you write something like this

assert someValue != null : "some value should be set"

It means that you have written your code in such a way that someValue gets set one way or the other, and by the time the code reaches assert it must be set.

If someone modifies your code so that it could reach the assert without setting someValue, the assertion would catch it.

Your code, on the other hand, tries to use assertions for validations for which exceptions are there for:

Check this:

public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.println("Enter your age?");
		int age = sc.nextInt();
		try {
			if (age <= 18) {
				throw new InvalidAgeException("User can not vote");
			}
		} catch (InvalidAgeException e) {
			e.printStackTrace();
		}
		System.out.println("Age entered by user is " + age);
		sc.close();
	}

It depends whether you want to verify something and throw AssertionError for later correction in the code or throw the error and handle the error so that code moves fine and just logs the error. Depends how you want your code to run. Run the above code.