The usage of assert in Java and Javaassert
1. assert booleanExpression; if it is true, the program continues to execute; otherwise, a java. lang. AssertionError is thrown and the program is terminated.
2. assert booleanExpression: errorMessage; if it is true, the program continues to execute; otherwise, a java. lang. AssertionError is thrown, and the error message is printed and the execution program is terminated.
To enable the assert function in eclipse, you must
- Go to Run-> run configuration
- Select java application in left nav pan.
- Right click and select New.
- Select Arguments tab
- Add-ea in VM arguments.
How to Use assert in java programming?
In Java, the assert keyword is introduced from java se 1.4. to avoid errors caused by the use of the assert keyword in Java code of earlier versions, by default, Java does not start assertion checks during execution (at this time, all assertion statements will be ignored !), If you want to enable the assertions check, you must enableassertions or-ea.
The syntax of the assert keyword is simple and has two usage methods:
1. assert <boolean expression>
If <boolean expression> is true, the program continues to execute. If it is false, the program throws an AssertionError and terminates the execution.
2. assert <boolean expression >:< error message expression>
If <boolean expression> is true, the program continues to execute. If it is false, the program throws a java. lang. AssertionError and enters the <error message expression>.
That is, you need to add the parameter-ea when executing the java command, as shown in figure
Java-ea xxx
It is not recommended for individuals.
When is assert used? In java
Assertion is a common debugging method used in software development. Many programming languages support this mechanism. In implementation, assertion is a statement in the program, it checks a boolean expression. A correct program must ensure that the value of this boolean expression is true. If the value is false, the system will give a warning or exit when the maze program is in an incorrect state. Generally, assertion is used to ensure the most basic and critical correctness of the program. The assertion check is usually started during development and testing. To improve efficiency, the assertion check is usually closed after the software is released.
Hope to help you. Thank you!