Java Trap assert keyword detailed _java

Source: Internet
Author: User
Tags assert exception handling terminates java web java se

I. Overview

There are assert keys in both C and C + + languages, which represent assertions.
In Java, there is also an ASSERT keyword, which means that the assertion, usage, and meaning are similar.

Second, the grammar

In Java, the Assert keyword was introduced from Java SE 1.4 to avoid an error in the use of the Assert keyword in the old version of Java code, which by default does not initiate an assertion check (at which point all assertion statements are ignored!). If you want to turn on the assertion check, you need to switch-enableassertions or-ea to open it.

The Assert keyword syntax is simple and has two uses:

1. Assert <boolean expression >
If the <boolean expression > is True, the program continues to execute.
If False, the program throws a assertionerror and terminates execution.

2. Assert <boolean expression >: < error message expression >
If the <boolean expression > is True, the program continues to execute.
If False, the program throws Java.lang.AssertionError and enters < error message expression >.

Iii. Examples of application

Here is an example to illustrate its use:

Copy Code code as follows:

public class Assertfoo {
public static void Main (String args[]) {
Assertion 1 evaluates to true, proceed down
Assert true;
System.out.println ("Assertion 1 no problem, go! ");

System.out.println ("\ n-----------------\ n");

Assertion 2 evaluates to False, program terminates
Assert false: "The assertion failed, and the information for this expression will be output when the exception is thrown!" ";
System.out.println ("Assertion 2 no problem, go! ");
}
}




Save the code to C:\AssertFoo.java, and then follow the instructions below to view the console output:





1, compile the program:
C:\&gt;javac Assertfoo.java





2, the default execution procedure, does not turn on the-EA switch:
C:\&gt;java Assertfoo


Assertion 1 No problem, go!





-----------------





Assertion 2 No problem, go!





3, open-ea switch, the implementation of procedures:
C:\&gt;java-ea Assertfoo


Assertion 1 No problem, go!





-----------------





Exception in thread "main" Java.lang.AssertionError: Assertion failed, information for this expression will


Will output when the exception is thrown!


At Assertfoo.main (assertfoo.java:10)





Four, traps



Assert keywords are simple to use, but using an assert often leads you into a deeper trap. Use should be avoided. After research, the author summarizes the following reasons:





1. The Assert keyword needs to be explicitly opened at runtime to be effective, otherwise your assertion has no meaning. Now the mainstream Java IDE tools do not have the-ea assertion check enabled by default. This means that if you use the IDE tool to encode, debugging run time will be a certain amount of trouble. And, for Java Web applications, the program code is deployed in the container, you can not go directly to the control program, if you have to open the-EA switch, you need to change the Web container run configuration parameters. This is a great inconvenience to porting and deploying programs.





2, the use of assert instead of if is the trap of the second. Assert judgments are similar to if statements, but their roles are essentially different: The Assert keyword is intended to be used to test the debugger, but if you accidentally control the program's business process with assert, Removing the Assert keyword after the test is finished means modifying the normal logic of the program.





3, Assert assertion failure will face the exit of the program. This application in a production environment is absolutely intolerable. Typically, exception handling is used to resolve potential errors in the program. But using assertions is dangerous, and once the system fails, it hangs.








v. Reflections on the Assert



Assert is for the purpose of debugging test program, not in the formal production environment, that should consider better test juint to replace it, Juint relative assert key to provide the function is even more. Of course, debug tests can be done through IDE Debug. In this view, the future of the assert is dim.





Therefore, you should avoid using the Assert keyword in Java, except when the Java default supports opening-ea switches. By contrast, the principle that assert can bring you how much benefit, how much trouble, this is we choose whether to use.





============================================================


Comment


Conversely, in some open source components, such as validator, JUnit, the judgment process seems to use the assertion style, it is possible to use a large number of assertions, but the author did not see the source code before not sure.


If it's a simple test in the development phase, JUnit is a handy and powerful tool, and there's no reason to write assertions without using it.





============================================================


Comment


It can be used first in the unit test code. JUnit intrusion is strong and it is difficult to remove or select another frame if the entire project has a large amount of code that uses JUnit. If you have a lot of unit test code and want to reuse these unit test cases, you should select Assert rather than junit to facilitate the use of other unit test frameworks, such as testng. Similarly, formal functional code should not appear in JUnit at all, and should use assert.





Assert is mainly suitable for base class, Framework class, interface class, Core code class, tool class. In other words, when the caller of your code is another programmer writing business code, or another subsystem, it is necessary to use it. Like you did a quick sort of algorithm

Copy Code code as follows:

public static list<int> QuickSort (list<int> List) {
Assert list!= null;
Apply for temporary space
Start sorting
for (int i:list) {
//
}
}



In this case, if you do not check the correctness of the incoming parameter, you will throw an inexplicable null pointer error. Your caller may not be aware of the details of your code, and it is a waste of time to debug a null pointer error in the depths of a system. It should be directly clear to your caller that there is a problem with the incoming parameter. Otherwise he will suspect that your code has bugs. Using assert prevents two programmers from blaming each other for written code that is problematic.

Assert applies to errors that you know specifically what errors you and your caller have agreed should be excluded or checked by your caller. You tell your caller by an assertion. Assert does not apply to errors caused by external systems, such as user input data errors, or an external file format error. These errors are not caused by your caller but by the user, and are not even exceptions because of the frequent input errors and file format errors that should be checked by the business code.

Assert is better suited to the frequently invoked base class, framework code, tool class, core code, interface code, which is why it was removed at runtime. The test code should open the-ea parameter in the test phase to make careful testing of the core code in the deep system.

The reason Java uses less assert is that Java has a very complete OO system, forcing type conversions to appear less frequently, so it does not need to be as frequent as C to check whether the pointer is of the correct type and whether the pointer is empty. Java also rarely manages memory or buffers directly, so it does not require frequent checks to see if the incoming buffer is empty or is out of bounds.

But using a good assert can help improve the correctness of the frame code and reduce the user's debugging time for the frame code.

===============================================================
Comment
The purpose of assert is to make it easy for programmers to discover their own logic errors without affecting the efficiency of the program. The errors found by assert are completely inappropriate and cannot be replaced with exceptions. Exception, which is allowed by the system, or the system is not controllable "error", it is not a programmer's logical problem.

The assert should be open during the development phase and closed after publication.

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.