Java Reference
In-Depth Information
be checked.
• Assertions also prevent appropriate exceptions from being thrown. For ex-
ample, when an illegal argument is passed to a public method, it is common
tothrow IllegalArgumentException or NullPointerException .
However, AssertionError is thrown instead.
You should also avoid using assertions to perform work required by the application
to function correctly. This work is often performed as a side effect of the assertion's
Boolean expression. When assertions are disabled, the work is not performed.
Forexample,supposeyouhavealistof Employee objectsandafewnullreferences
not be correct to remove these references via the following assertion statement:
assert employees.removeAll(null);
Although the assertion statement will not throw AssertionError because there
isatleastonenullreferenceinthe employees list,theapplicationthatdependsupon
this statement executing will fail when assertions are disabled.
better off using code similar to the following:
boolean allNullsRemoved = employees.removeAll(null);
assert allNullsRemoved;
or disabled, and you can still specify an assertion to verify that nulls were removed.
Enabling and Disabling Assertions
The compiler records assertions in the classfile. However, assertions are disabled at
runtime because they can affect performance. An assertion might call a method that
takes awhile to complete, and this would impact the running application's performance.
You must enable the classfile's assertions before you can test assumptions about the
behaviors of your classes. Accomplish this task by specifying the -enableasser-
tions or -ea command-lineoptionwhenrunningthe java applicationlaunchertool.
The -enableassertions and -ea command-line options let you enable asser-
oargument scenario, you must use a colon to separate the option from its argument):
No argument : Assertions are enabled in all classes except system classes.
Search WWH ::

Custom Search