The assertion of Java

Source: Internet
Author: User

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

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.