The concept of assertions
Asserts the assumption used to prove and test a program, such as "the value here is greater than 5".
Assertions can be completely removed from code at run time, so there is no effect on the speed at which the code runs.
Use of assertions
There are two ways of asserting:
One is the assert<< boolean expression >>;
The other is assert<< Boolean expression >>:<< detail Description >>.
If the Boolean expression evaluates to False, the Assertionerror exception is thrown; the description text of the ASSERTIONERROR exception is compiled using the Javac–source 1.4 Myclass.java sample as follows:
public class Assertexample {public
static void Main (string[] args) {
int x = ten;
if (Args.length > 0) {
try {
x = Integer.parseint (args[0]);
} catch (NumberFormatException nfe) {/
* Ig Nore *
/}
System.out.println ("testing assertion that x = = ten");
assert x = =: "Our assertion failed";
System.out.println ("Test passed");
}
Because a new keyword has been introduced, additional parameters need to be added at compile time, and to be successful, you must use the JDK1.4 Javac and add the parameter '-source 1.4 ', for example, you can compile the above code with the following command:
Javac-source 1.4 Assertexample.java
The above program runs using the Assert feature also requires additional parameters (and requires a number of command-line arguments), for example:
The output of the program is:
Testing assertion that x = =
Exception in thread ' main ' Java.lang.AssertionError:Our assertion failed at
Asserte Xample.main (ASSERTEXAMPLE.JAVA:20)
Because the input parameter is not equal to 10, the assertion function causes the program to run with an assertion error, noting that it is an error, which means that the program has a fatal error and will force the exit. The assertion uses a Boolean value that throws a Assertionerror and terminates the program's operation if its value is not true.
Assertion recommended methods of use
Used to verify the internal logic in the method, including:
- Intrinsic invariant type
- The control flow does not change the type
- Post condition and class invariant
Note: It is not recommended to check for a precondition in a public method.
run-time masking assertion
To mask assertions at run time, you can use the following method:
java–disableassertions or Java–da class name
to allow assertions at run time, you can use the following method:
java–enableassertions or Java–ea class name