Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable Java assertions in Visual Studio Code

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?

like image 264
anothernode Avatar asked Jan 03 '19 14:01

anothernode


People also ask

How can we enable assertions to Debug your code in Java?

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.

How do I get Java to work on Vscode?

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.

Can assertion be enabled for packages in Java?

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.


1 Answers

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"
        }
    ]
}
like image 140
anothernode Avatar answered Oct 12 '22 10:10

anothernode