Exception Handling Policy – Using Assertions

This is the second part in a series of four on exception handling and it focuses on an area related to exceptions — assertions.

A quick summary of posts in this series:

  1. Throwing Exceptions
  2. Using Assertions (this one)
  3. Catching Exceptions
  4. Logging Exceptions

Guidelines for assertions

An assertion is code that’s used during development that allows a program to check itself as it runs. They are used much in the same spirit as unit tests, but spread out in the actual program code. It is a statement placed to indicate that the developer thinks that some predicate is always true at that place.

Use assertions for conditions that should never occur

If an assertion is fired for an anomalous condition, the corrective action is not merely to handle an error gracefully — the corrective action is to change the program’s source code, recompile, and release a new version of the software.

Use assertions to document and verify preconditions and postconditions.

Use a barricades to distinguish between assertions and exceptions

Routines that are outside the barricade should use error handling because it isn’t safe to make any assumptions about the data. Routines inside the barricade should use assertions, because the data passed to them is supposed to be sanitized before it’s passed across the barricade. If one of the routines inside the barricade detects bad data, that’s an error in the program rather than an error in the data.

Don’t put executable code into assertions.

Doing so raises the possibility that the compiler will eliminate the code when you turn off the assertions. Instead, only put boolean conditions with no side effects in your assertions.

For highly robust code, assert and then handle the error any way

Better safe than sorry, they say.

Assertions in Java

For those unfamiliar with assertions, I’ll give a quick summary. Java provides the keyword assert since version 1.4. It throws a java.lang.AssertionError when it fails, and has the following syntax:

assert expression : "error message shown if expression is false";

Where expression is any boolean expression which should always be true at the point of the assertion. For example, this variable should always be greater than 0, or that collection should always be empty.

To enable assertions when running a program, use the Java VM -ea (or -enableassertions) switch. Assertions are always compiled in, but without this switch, the assertions are ignored by the virtual machine.

Tune in next week for guidelines for catching exceptions! And please do write any comments or questions you might have below.