Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Assertion Question

Tags:

java

What exactly happens when a Java assertion fails? How does the programmer come to know that an assertion has failed?

Thanks.

like image 339
Student Avatar asked Apr 16 '11 16:04

Student


People also ask

What is assertion give example in Java?

An assertion allows testing the correctness of any assumptions that have been made in the program. An assertion is achieved using the assert statement in Java. While executing assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError.

What are assertion in Java?

An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.

How do you write assertion in Java?

An assertion is made using the assert keyword. Its syntax is: assert condition; Here, condition is a boolean expression that we assume to be true when the program executes.


3 Answers

If assertions are enabled in the JVM (via the -ea flag), an AssertionError will be thrown when the assertion fails.

This should not be caught, because if an assertion fails, it basically means one of your assumptions about how the program works is wrong. So you typically find out about an assertion failure when you get an exception stack trace logged with your thread (and possibly whole program) terminating.

like image 197
Simon Nickerson Avatar answered Oct 10 '22 18:10

Simon Nickerson


An assertion will only fail if you enabled assertions in the JVM when it started. You can do that by specifying the parameter -ea in the command line. If you do that, then this block of code will throw an AssertionError when it is executed:

public void whatever() {
   assert false;
}

Assertions should be used to detect programming errors only. If you are validating user input or something on those lines, don't use assertions.

like image 21
Ravi Wallau Avatar answered Oct 10 '22 16:10

Ravi Wallau


It throws an AssertionError which is a subclass of Error. As an Error generally and as a failed assertion in particular, you likely should not try to catch it since it is telling you there's a significant abnormality in your code and that if you continue you'll probably be in some undefined, unsafe state.

like image 29
QuantumMechanic Avatar answered Oct 10 '22 18:10

QuantumMechanic