Test programs using Java assertions

Source: Internet
Author: User

Assertions are introduced at the beginning of j2se 1.4. The syntax is as follows:

Assert <logical expression>

Assert <logical expression >:< information expression>

The first syntax throws an assertionerror when the logical expression is false. The second syntax prints the value of the information expression while throwing an exception.

 

Assertion Compilation

If j2se 1.4 is used, the compiler must be told to Use assertions. The syntax is as follows:

Javac-source 1.4 <Source File>

If javase 5.0 and later versions are used, no special instructions are required. To disable assertions, add the following description:

Javac-source 1.3 <Source File>

 

Enable assertions during runtime

Run the following command:

Java-Ea <Class Name>

 

When to use assertions

The purpose of assertion is to checkProgramThe logic is correct, not to implement the logic. If the assertions are disabled during runtime and affect the function of the program, the assertions are abused. Note the following when using assertions:

1. The state of the program remains unchanged before and after the expression is used. For example, you cannot use operations that affect the running status in an asserted expression, such as "++" or;

2. assertion failure is caused by a program logic error. You should modify the program, rather than capture and process assertion failure;

3. The asserted check should only be used in the development and test phase, and should not be used in the formal running environment.

 

 

 

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.