About JDK1.4 increased ASSERT statement

xiaoxiao2021-03-06  101

About JDK1.4 increased ASSERT statement

1. Syntax for Assert statement

JDK1.4 adds an ASSERT statement, its syntax is as follows:

askSERT Assumption or

Assert Assumn: Error Message Or Error Code

Assumption should be a Boolean value. (Or the conditional expression, anyway, the final result is true or false.)

If assumption is true, then everything is as usual, this statement is like not appearing, if Assumption is false, then the program will throw a java.lang.AssrtionError. If the second type of Error Message or Error Code is used in the code, the error message or ERROR Code will follow Java.lang.AsSsertionError.

2. Compile with code with assert statement

If you use the assert statement in your code, you should use Javac to compile like this:

Javac -Source 1.4 **. Java

Otherwise, the assert keyword will not be considered keyword. (This is because the Assert statement is from JDK1.4

There is only one. )

Of course, Warning will appear when you use JDK1.4 and above.

3. Start the assert when running.

By default, ASSERT is not enabled.

This should be such asserts when running:

Java -ea: Classified class name

or

Java -ea: package name ... class name

The corresponding use-DA is closed assert.

(You can refer to the gang group of the java command).

4. Benefits and use of Assert.

I thought Assert mainly used to debug. It is easy to locate errors using it. In addition, in the appropriate place of the code, the ASSERT statement can be used, and the rapid positioning code is rapidly positioned when the value range of certain values ​​in the code is changed, and the bug of the code is found. Please see the following example.

Suppose I now take 0 and 1.

So we can write this code:

IF (0 == i) {

....} else {// i == 1

...

}

When the value of I changes (this is completely possible, because the value of this i may be the parameters passing by other modules.), This code is very likely to have potential bugs, and this bug does not necessarily Can be expressed immediately. It is not easy to locate this error even if it is. Because you are likely to be firmly believed to be 0 or 1.

But if the above code is changed to this:

IF (0 == i) {

....} else {// i == 1

askERT I == 1: "The i value isn't 0 or 1."

.

}

So once the value of I exceeds 0, 1, then immediately throws java.lang.assertionError with error message. This is clear at a glance.

5. Finally write an example of running:

Public class testassert {

Public static void main (string [] args) throws exception {

INT i = 100;

String ErrorMsg = "this is a error";

INT ErrorCode = 10000;

ASSERT I> 200: ErrorCode;

ASSERT I> 200: ERRORMSG;

}

}

Then compile:

Javac -Source 1.4 Testassert.java

Then run:

Java -ea: Testassert Testassert

The results of the operation are as follows:

转载请注明原文地址:https://www.9cbs.com/read-123458.html

New Post(0)