14) Assert in Java, 14) JavaAssert

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.