Introduction to JVM Languages
上QQ阅读APP看书,第一时间看更新

-ea to enable assertions

With this option, assertions can be enabled (by default, they are turned off).

In a language that supports assertions, the programmer can add runtime conditional checks. In Java, this is done by adding an assert statement, followed by a condition. When assertions are disabled, these statements are ignored completely, but when enabled, the JVM throws an error if the condition turns out to be false. This can be used to check whether the program works as expected. An example of an assert statement in Java:

    int i = 25;

assert i < 24;

When assertions are enabled with the -ea option, the preceding code will result in a java.lang.Error instance thrown by the JVM once the assert statement runs. When not explicitly specified on the command line, the preceding code will run fine.

Assertions can be enabled globally and also per package with the -ea:PACKAGE form, where PACKAGE must be substituted with the full package name. You can add the -ea:PACKAGE option to each package that you want assertions enabled for.

Writing unit tests is considered a better mechanism to thoroughly test code, but asserts can still come in handy in some situations.