What exactly happens when a Java assertion fails? How does the programmer come to know that an assertion has failed?
Thanks.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With