14) Assert in Java, 14) JavaAssert
J2SE 1.4 provides a new feature in terms of language, namely the assertion (assertion) function, which is the biggest innovation of this version in the Java language. In software development, assertion is a classic debugging and testing method. Jvm assertions are disabled by default.
Assertions can be partially enabled. For example, the parent class prohibits assertions, while the Child class enables assertions. Therefore, "assertions do not have inheritance ".
Assertions are only applicable to complex Debugging Processes.
Assertions are generally used to determine the execution result of a program. Never let them process business processes. The entire program can still run correctly after removing the assert statement.
Assertion usage
1st usage methods:
Public static void main (String [] args ){
Boolean isOk = 1> 2;
Assert isOk;
System. out. println ("program normal ");
}
Because 1> 2 is obviously incorrect, the execution result throws an Exception: Exception in thread "main" java. lang. AssertionError
If you change 1> 2 to 1 <2, the program will run smoothly and print "the program is normal"
2nd usage methods:
Public static void main (String [] args ){
Boolean isOk = 1> 2;
Try {
Assert isOk: "program error ";
System. out. println ("program normal ");
} Catch (AssertionError err ){
System. out. println (err. getMessage ());
}
}
Assert is followed by a colon expression. If the value is true before the colon, the value after the colon is ignored.
If the value is false before the colon, AssertionError is thrown. The error message is the content after the colon. The preceding program execution result is printed: "program error"