A brief analysis of the use of assertions in Java exception handling

  • 2020-04-01 04:12:45
  • OfStack

Concept of assertion

Assertions are used to prove and test a program's assumptions, such as "the value here is greater than 5."
Assertions can be completely removed from the code at run time, so there is no impact on the speed of the code.
Use of assertions

There are two ways to assert:
One is assert< < Boolean expression > > ;
The other is assert< < Boolean expression > > : < < Detail description > > .
If the Boolean expression is false, an AssertionError exception is thrown. The detail description is the text describing the AssertionError exception compiled using the javac copysource 1.4 myclass.java method as follows:


public class AssertExample {
  public static void main(String[] args) {
    int x = 10;
    if (args.length > 0) {
      try {
        x = Integer.parseInt(args[0]);
      } catch (NumberFormatException nfe) {
        
      }
    }
    System.out.println("Testing assertion that x == 10");
    assert x == 10 : "Our assertion failed";
    System.out.println("Test passed");
  }
}

Since a new keyword has been introduced, additional parameters need to be added at compile time. To compile successfully, you must use JDK1.4 javac and add the parameter '-source 1.4'. For example, you can compile the above code using the following command:
   


 javac -source 1.4 AssertExample.java


The above program also requires additional parameters (and a numeric command-line parameter) to run using the assertion function, such as:


  java -ea AssertExample 1


The output of the program is:


Testing assertion that x == 10
Exception in thread "main" java.lang.AssertionError:Our assertion failed
at AssertExample.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, which is an error, meaning that the program has a serious error and will force an exit. The assertion USES a Boolean value, which throws an AssertionError and terminates the program if it is not true.
Assertions are recommended

Used to validate the internal logic in the method, including:

Intrinsic invariant Control flow invariant Postconditions and class invariants

Note: checking preconditions in public methods is not recommended.
Runtime masking assertions

To mask assertions at runtime, use the following method:
      Java with disableassertions or Java with da class name
To allow assertions at runtime, use the following method:
      Java options enableassertions or Java options class name


Related articles: