Using assertions

Refer to the article Programming With Assertions (from Oracle) for more details on the three general guidelines below.

  1. Do not use assertions to do any work that your application requires for correct operation.
    If you do, the code will not work as expected when assertions are turned off.

  2. Do not use assertions for checking preconditions/parameters in public methods.
    Those should be enforced by explicit checks that throw particular, specified exceptions. e.g. IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException.

  3. Assertions may be used to check postconditions and class/method invariants in both public and nonpublic methods.

In addition,

  • Do not handle 'impossible' exceptions using assertions.
    Instead of handling 'impossible' exceptions using an assert false as given below, throw a runtime error such as an AssertionError.

image

...
} catch (Exception e) {
    assert false : "This exception should not happen";
}

image

...
} catch (Exception e) {
    throw new AssertionError("This exception should not happen");
}
Rationale

As the program flow has already triggered an exception, switching to assertions is not necessary when another exception can handle it just as well.