Java Reference
In-Depth Information
To use assertions effectively, you must also be aware of a couple of fine points. First,
remember that your programs will normally run with assertions disabled and only
sometimes with assertions enabled. This means that you should be careful not to
write assertion expressions that contain side effects.
You should never throw AssertionError from your own
code, as it may have unexpected results in future versions
of the platform.
a x
If an AssertionError is thrown, it indicates that one of the programmer's assump‐
tions has not held up. This means that the code is being used outside of the parame‐
ters for which it was designed, and it cannot be expected to work correctly. In short,
there is no plausible way to recover from an AssertionError , and you should not
attempt to catch it (unless you catch it at the top level simply so that you can display
the error in a more user-friendly fashion).
Enabling assertions
For efficiency, it does not make sense to test assertions each time code is executed—
assert statements encode assumptions that should always be true. Thus, by default,
assertions are disabled, and assert statements have no effect. The assertion code
remains compiled in the class files, however, so it can always be enabled for diag‐
nostic or debugging purposes. You can enable assertions, either across the board or
selectively, with command-line arguments to the Java interpreter.
To enable assertions in all classes except for system classes, use the -ea argument.
To enable assertions in system classes, use -esa . To enable assertions within a spe‐
cific class, use -ea followed by a colon and the classname:
java - ea: com . example . sorters . MergeSort com . example . sorters . Test
To enable assertions for all classes in a package and in all of its subpackages, follow
the -ea argument with a colon, the package name, and three dots:
java - ea: com . example . sorters ... com . example . sorters . Test
You can disable assertions in the same way, using the -da argument. For example, to
enable assertions throughout a package and then disable them in a specific class or
subpackage, use:
java - ea: com . example . sorters ... - da: com . example . sorters . QuickSort
java - ea: com . example . sorters ... - da: com . example . sorters . plugins ..
Finally, it is possible to control whether or not assertions are enabled or disabled at
classloading time. If you use a custom classloader (see Chapter 11 for details on cus‐
tom classloading) in your program and want to turn on assertions, you may be
interested in these methods.
Search WWH ::

Custom Search