Impetus: It Services Private Limited
Impetus: It Services Private Limited
When the runtime execute the assertion, it first evaluates the booleanExpr. If the value is true, nothing
happens. If it is false, the runtime throws an AssertionError, using the no-argument constructor (in
the first form) or errorMessageExpr as the argument to the constructor (in the second form). If an
object is passed as the errorMessageExpr, the object's toString() will be called to obtain the
message string.
Assertion is useful in detecting bugs. It also serves to document the inner workings of you program
(e.g., pre-conditions and post-conditions) and enhances the maintainability.
One good candidate for assertion is the switch-case statement where the programmer believes that one
of the cases will be selected, and the default-case is not plausible. For example,
Assertion, by default, are disabled to ensure that they are not a performance liability in the production
environment. To enable assertion, use the runtime command-line option enableassertions (or ea).
In the above example, "assert false" always triggers an AssertionError. However, the output is
different, depending on whether assertion is enabled or disabled.
> javac AssertionSwitchTest.java // no option needed to compile
> java -ea AssertionSwitchTest // enable assertion
5 % 6 = 0
In the above example, since the "assert false" always triggers an AssertionError, you could choose
to throw an AssertionError. "throw" is always enabled during runtime.
Another usage of assertion is to assert "internal invariants". In other words, to assert the possible values
of an internal variable. For example,