3.7. Assertions

Every so often you will find that the logic in your code leads to some logical condition that should always be true. If you test an integer and establish that it is odd, it is certainly true that it cannot be even, for example. You may also find yourself writing a statement or statements that, although they could be executed in theory, in practice they never really should be. I don't mean by this the usual sorts of errors that occur, such as some incorrect data being entered somehow, which should be handled ordinarily by the normal code. I mean circumstances where if the statements were to be executed, it would imply that something was very seriously wrong with the program or its environment. These are precisely the circumstances to which assertions apply.

A simple assertion is a statement of the form

assert logical_expression;

Here, assert is a keyword, and logical_expression is any expression that results in a value of true or false. When this statement executes, if logical_expression evaluates to true, then the program continues normally. If logical_expression evaluates to false, the program will be terminated with an error message starting with:

java.lang.AssertionError

This will be followed by more information about where the error occurred in the code. When this occurs, the program is said to assert.

Let's consider an example. Suppose you have a variable of type int that stores the number of days in the current month. You might use it like this:

if(daysInMonth ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.