Usage of assert statement in Java

Assert is a special construct that allows you to test assumptions about the values ​​of arbitrary data anywhere in your program. An assertion can automatically signal the detection of invalid data, which usually leads to an abnormal program termination with an indication of where the invalid data was found.

Assertions greatly simplify the localization of errors in your code. Even checking the results of executing obvious code can be useful for subsequent refactorings, after which the code may become less obvious and an error may creep into it.

Typically, assertions are left on during development and testing of programs, but off in release versions of programs.

Because assertions can be removed at compile time or at runtime; they should not change the behavior of the program. If the behavior of the program may change as a result of removing the assertion, then this is a clear sign of misuse of assert. Thus, inside assert, you cannot call methods that change the state of the program or the external environment of the program.

In Java, assertion checking is implemented using the assert statement, which has the form:

assert [Expression of type boolean];
or
assert [Expression of type boolean]: [Expression of any type other than void];

During program execution, if assertion checking is enabled, the value of the boolean expression is evaluated, and if its result is false, then a java.lang.AssertionError exception is thrown. In the case of using the second form of the assert operator, the expression after the colon specifies a detailed message about the error that occurred (the evaluated expression will be converted to a string and passed to the AssertionError constructor).


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed