THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

12.10.1. Why Turn Assertions On and Off?


The first question to answer is why you would want to be able to switch assertion evaluation on and off. The
usual example is to turn assertions on during development, but turn them off when your system is shipping.
The argument is that you will have caught any insanities during the development cycle so the overhead of
doing all the checks is not worth the effort.


This is tempting logic, but you can open yourself up to serious problems. The point of assertions is to catch
bugs early before they corrupt things and cause bizarre side effects. When someone else is running your code,
tracking down causes for problems is much more difficult, so catching them early and reporting them clearly
is much more important, even if it should happen a lot less often. You should only turn off assertions in code
where they have very noticeable performance effects. In those critical sections of code, though, you will want
to turn them off.


12.10.2. Controlling Assertions on the Command Line


Assertion evaluation is off by default. To change this, you can use standard command line options if you are
using a command-line-driven virtual machine:


-enableassertions/-ea[descriptor]

Enables (turns on) assertion evaluation as defined by the descriptor. If
there is no descriptor, assertions are enabled for all classes except those
loaded by the system class loadersee "Loading Classes" on page 435.

-disableassertions/-da[descriptor]

Disables (turns off) assertion evaluation for all classes as defined by the
descriptor. If there is no descriptor, assertions are disabled for all
classes.

The descriptor allows you to specify particular packages or classes that will be affected by the option. An
absent descriptor means the option applies to all non-system classes (that is, classes loaded by any class loader
but the system class loader). Packages are defined by name, followed by ... which means to apply the
option to all subpackages. For example, the option


-enableassertions:com.acme...


would turn on assertions in all classes in com.acme and all its subpackages. If the descriptor consists only of
... it represents the unnamed package in the current working directory. Without the ... the descriptor is
assumed to be the full name of a class.


-enableassertions:com.acme.Plotter


turns on assertions for the class com.acme.Plotter. So if you want to turn on all assertions in
com.acme, but the class com.acme.Evalutor is not relevant, you could say


-enableassertions:com.acme... -da:com.acme.Evaluator

Free download pdf