Java's assert (assertion)

We know that there is an assertion function (assert) in the C/C++ language. The assertion feature has also been added in Java SE 1.4 and later.

Assertions are for the convenience of debugging the program and are not part of the released program. Understanding this is critical.

By default, JVM disables assertions. Therefore, if you want to use assertion debugging, you need to manually turn on the assertion function. When running a Java program in command line mode, you can add the parameter -enableassertions or -ea to turn on assertions. Assertions can be turned off via -disableassertions or -da (default, optional).

Use of assertions:

Assertion is defined through the keyword assert. Generally, it has two forms.

1. assert <bool expression>;       比如     boolean isStudent = false; assert isStudent;

2. assert <bool expression> : <message>;    比如  boolean isSafe = false;  assert isSafe : "Not Safe at all";

It’s useless to just talk, here are a few simple examples:

First form:

public class AssertionTest {
 
	public static void main(String[] args) {
		
		boolean isSafe = false;
		assert isSafe;
		System.out.println("断言通过!");
	}
}

If you are running in command line mode, you need to specify to enable the assertion function. like

java -ea AssertionTest


If you are under an IDE, such as Eclipse, you can set it like this: Run as -> Run Configurations -> Arguments -> VM arguments: type -ea.

Output result:

Exception in thread "main" java.lang.AssertionError
	at AssertionTest.main(AssertionTest.java:8)


 

Second form:

public class AssertionTest {
 
	public static void main(String[] args) {
		
		boolean isSafe = false;
		assert isSafe : "Not safe at all";
		System.out.println("断言通过!");
	}
}


Output result:

Exception in thread "main" java.lang.AssertionError: Not safe at all
	at AssertionTest.main(AssertionTest.java:7)


The difference between the second form and the first is that the latter can specify error information.

trap:

Assertions are only for debugging the program, do not write assertions into business logic. For example, consider the following simple example:

public class AssertionTest {
 
	public static void main(String[] args) {
		
			assert ( args.length > 0);
			System.out.println(args[1]);
	}
}


The sentence assert (args.length >0) has a similar meaning to if (args.length >0), but if the program is released (asserts are generally not turned on), this sentence will be ignored, resulting in the following

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
	at AssertionTest.main(AssertionTest.java:7)


Better alternatives:

JUnit。

Guess you like

Origin blog.csdn.net/weixin_39827856/article/details/131293417