J2SE 1.4 provides a new feature in the language, which is the assertion (assertion) feature, which is the biggest innovation in the Java language for this version. In the software development, assertion is a kind of classic debugging, testing way. The JVM assertion is turned off by default.
Assertions can be locally opened, such as: The parent class suppresses assertions, and subclasses open assertions, so it is generally said that "assertions do not inherit."
Assertions apply only to complex debugging procedures.
Assertions are generally used to judge the results of program execution,never let assertions handle business processes。 The entire program can still run correctly after the Assert statement is removed.
Assertion Use Method
1th method of Use:
public static void Main (string[] args) {
?? Boolean isOk = 1>2;
?? Assert isOk;
?? SYSTEM.OUT.PRINTLN ("normal procedure");
}
Because 1>2 is obviously wrong, the execution result throws an exception: Exception in thread "main" Java.lang.AssertionError
If you change the 1>2 to 1<2 then the program can execute smoothly, printing "program normal"
The 2nd method of use:
public static void Main (string[] args) {
???? Boolean isOk = 1>2;
???? try{
?????????? Assert isOk: "Program error";
?????????? SYSTEM.OUT.PRINTLN ("normal procedure");
??????? }catch (Assertionerror err) {
????????? System.out.println (Err.getmessage ());
???? }
}
The assert is followed by a colon expression. If true before the colon, it is ignored after the colon.
If False before the colon, throws a assertionerror, the error message content is after the colon content, the above program execution result is printing: "Program error"
+) assert in Java