EN
Java - how to enable assertions?
14
points
In this article we whould like to show how to enable assertions in Java.
The article describle 2 ways how to do it:
- with command line (terminal),
- with IntelliJ IDE.
Read below sections to see details.
1. Java with command line example
Running program from console it is necessary to add -ea
or -enableassertions
paramter for java virtual machine to use assertions.
Program.java
file:
public class Program {
public static void main(String[] args) {
String a = "text"; // or = null by default
// some code...
a = null; // for example: some operation caused null value
// some code...
assert a != null : "Variable can not be null";
System.out.println(a.length());
}
}
1.1. Compilation form console:
$ javac Program.java
1.2. Running from console:
$ java -ea Program
or
$ java -enableassertions Program
Output:
Exception in thread "main" java.lang.AssertionError: Variable can not be null
at Program.main(Program.java:12)
2. IntelliJ IDEA compilation example
IntelliJ requires to add in Run/Debug Configurations window, -ea
or -enableassertions
paramter VM Options field.