How to Enable the Java Keyword Assert in Eclipse Program-Wise

How to enable the Java keyword assert in Eclipse program-wise?

To be specific:

  • Go to Run->run configuration
  • select java application in left nav pan.
  • right click and select New.
  • select Arguments tab
  • Add -ea in VM arguments.

Sample Image

Java - How to view assert messages in Eclipse

You might not have enabled assertions at the JVM level (with the -ea switch).
If you haven't, then this would explain the behaviour you are seeing. Try making the assertion false and see if anything appears on the console.

Also have a look at the following questions & answers for more detail:
* See What does the "assert" keyword do?

What does the Java assert keyword do, and when should it be used?

Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea option on the java command, but are not turned on by default.

An example:

public Foo acquireFoo(int id) {
Foo result = null;
if (id > 50) {
result = fooService.read(id);
} else {
result = new Foo(id);
}
assert result != null;

return result;
}

Assert statement is not throwing exception

Assert are disabled unless you pass the -ea (enable assertions) command line option to the JVM.

For Eclipse, you may follow this link: Setting execution arguments

Add -ea to the VM arguments:

VM Arguments: Values meant to change the behavior of the Java virtual
machine (VM). For example, you may need to tell the VM whether to use
a just-in-time (JIT) compiler, or you may need to specify the maximum
heap size the VM should use. Refer to your VM's documentation for more
information about the available VM arguments.

Alternatively, this can be done widely on the JRE: Adding a new JRE definition

In the Default VM Arguments field, you can add/edit the default
arguments that will be passed to the VM when launching.

Java assertions in IntelliJ IDEA Community?

Based on this answer for Eclipse you need to pass a JVM option -ea to enable assertions in any JVM. It's not unique to any specific IDE.

For IntelliJ it looks like this in the run config:
IntelliJ 2020.3 Run Dialog to enter ea option

Note that you may have to select "Modify Options" to make the JVM options input box visible to enter the -ea flag.

Assert error in java

AssertionError isn't being thrown.

Add -ea (enabling assertions) to the Java command arguments when running your application.



Related Topics



Leave a reply



Submit