When running a Java program from the command line, assertions can be enabled with the -enableassertions
option for the java
command. Running this program would then (and only then) fail with an AssertionError
:
public class App {
public static void main(String[] args) throws Exception {
foo(2);
}
private static void foo(int x) {
assert x > 5;
System.out.println(x);
}
}
How can this be done when running a Java program in Visual Studio Code with the Java Extension Pack?
You should use the -ea or -enableassertions switch of Java To enable assertion. As an example, suppose you have a program written in Java stored in a file in the disk as Sample. java. Here is the sequence of statements you should execute in the command line to execute your program with assertion turned on.
In order to run Java within Visual Studio Code, you need to install a JDK. The Extension Pack for Java supports Java version 1.5 or above. We recommend you to consider installing the JDK from one of these sources: Amazon Corretto.
By default, assertions are disabled. Two command-line switches allow you to selectively enable or disable assertions. With no arguments, the switch enables assertions by default. With one argument ending in "...", assertions are enabled in the specified package and any subpackages by default.
Visual Studio Code manages launch configurations in the launch.json
file in the project folder root.
The -enableassertions
option can be added there with the vmArgs
key like this:
{
"configurations": [
{
"type": "java",
"name": "My App",
"request": "launch",
"mainClass": "App",
"projectName": "my-app",
"vmArgs": "-enableassertions"
}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With