Use assertions in eclipse

Source: Internet
Author: User

Assertion is a Java statement, Boolean expression,ProgramThe member thinks that the expression value should be true during program execution. The system calculates this Boolean expression to execute assertions. If this expression is false, the system reports an error.

Assertions are declared using the assert keyword. There are two formats for using the assert function:

Assert expression; or assert expression: detailmessage;

Expression is a Boolean expression, and detailmessage is a value of the basic data type or object type. When an asserted statement is executed, Java calculates the expression value. If its value is false, an assertionerror error is thrown.. For the second type of asserted statement with a detailed information, the assertionerror class will be used to construct a method that matches the Data Type of the message. Because the assertionerror class is a subclass of the error class, when the asserted value is false, the program will display a message on the console and terminate the program execution.

By default, the asserted function is not enabled in eclipse, so you will not see the effect when using the asserted function. First, use the following steps to enable the asserted function:

In myeclipse
Windows --> preferences ---> JAVA ---> installed jres ---> click the JDK in use ---> edit --->
Enter-ea in the default VM arguments text box

For example

 

After opening, use the followingCodeTest:

 Public   Class  Aseerttest {  Public   Boolean Flag = True ; //  Change the flag value and view the console output          Public   Boolean  Isvalid (){  Return  Flag ;}  Public  Static   Void  Main (string ARGs []) {aseerttest assertion = New  Aseerttest ();  Assert Assertion. isvalid (): "flag must be true! " ; System. Out. println ( "Assert end" );}} 

If you change the flag value to false to make the condition unable to pass the test, the following exception will be thrown, indicating that the asserted has taken effect.

 

Related Article

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.