Java Reference
In-Depth Information
Exceptions are one way to improve the reliability of your Java programs. Another way is
to use assertions—expressions that represent a condition that a programmer believes to
be true at a specific place in a program. If an assertion isn't true, an error results.
The
assert
keyword is followed by a conditional expression or Boolean value, as in this
example:
assert price > 0;
In this example, the
assert
statement claims that a variable named
price
has a value
greater than zero. Assertions are a way to assure yourself that a program is running cor-
rectly by putting it to the test, writing conditional expressions that identify correct behav-
ior.
The
assert
keyword must be followed by one of three things: an expression that is true
or false, a
boolean
variable, or a method that returns a
boolean
.
If the assertion that follows the
assert
keyword is not true, an
AssertionError
excep-
tion is thrown. To make the error message associated with an assertion more meaningful,
you can specify a string in an
assert
statement, as in the following example:
assert price > 0 : “Price less than 0.”;
In this example, if
price
is less than zero when the
assert
statement is executed, an
AssertionError
exception is thrown with the error message “Price less than 0”.
You can catch these exceptions or leave them for the Java interpreter to deal with. Here's
an example of how the JDK's interpreter responds when an
assert
statement is false:
Exception in thread “main” java.lang.AssertionError
at AssertTest.main(AssertTest.java:14)
Here's an example when an
assert
statement with a descriptive error message is false:
Exception in thread “main” java.lang.AssertionError: Price less than 0.
at AssertTest.main(AssertTest.java:14)
Although assertions are an official part of the Java language, they are not supported by
default by the tools included with the JDK, and the same may be true with other Java
development tools.
To enable assertions with the JDK, you must use command-line arguments when running
the interpreter.