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.
Running program from console it is necessary to add -ea
or -enableassertions
paramter for java virtual machine to use assertions.
Program.java
file:
xxxxxxxxxx
1
public class Program {
2
3
public static void main(String[] args) {
4
String a = "text"; // or = null by default
5
6
// some code...
7
8
a = null; // for example: some operation caused null value
9
10
// some code...
11
12
assert a != null : "Variable can not be null";
13
14
System.out.println(a.length());
15
}
16
}
xxxxxxxxxx
1
$ javac Program.java
xxxxxxxxxx
1
$ java -ea Program
or
xxxxxxxxxx
1
$ java -enableassertions Program
Output:
xxxxxxxxxx
1
Exception in thread "main" java.lang.AssertionError: Variable can not be null
2
at Program.main(Program.java:12)
IntelliJ requires to add in Run/Debug Configurations window, -ea
or -enableassertions
paramter VM Options field.



