Assertions are generally used for program self-protection.
1 Concepts of assertions:
I think the concept of assertion is not the meaning of determination, but the meaning of judgment. When we write a program, we sometimes want a value that fits our idea, and if that value doesn't fit our idea, we can correct it. (a bit around to see an example)
The above statement will be judged at run time.
In fact, the assertion is to solve this problem: we want to be able to test the time if a value does not meet our requirements, can throw an exception, meet our requirements, do nothing, and do not write any throw statement.
Java provides two forms (this process requires the use of the
Assert condition; and Assert condition:expression (if the condition is false throws a asserterror (which in fact belongs to the error in the exception system), the second one encapsulates the result of the expression in error)
This process needs to be used if we do not have parameters to go in, then the assertion will not open. Our problem is solved, if the test with parameters to determine the success, you can decide to run without parameters for processing.
2 Enabling and disabling assertions
The above has been said to enable assertion, which is disabled by default. Enabling assertions or disabling assertions does not have to be recompiled. Starting an assertion or disabling an assertion is a function of the ClassLoader, and the class loader ignores the assertion code when the assertion is disabled. So if we test well, it's equivalent to a code without any judgment, and the goal we wanted to achieve at the outset was achieved.
The following may be less of a use:
3 using assertions to complete parameter checking
There are three mechanisms in the Java language to handle system errors:
1 Throwing Exceptions
2nd log
3 Using Assertions
So when do you use assertions?
1 assertion of fatal, unrecoverable errors
2 assertions only for development and test phases
The assertion of Java