Using assertions
Refer to the article Programming With Assertions (from Oracle) for more details on the three general guidelines below.
-
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. -
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
, orNullPointerException
. -
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 anassert false
as given below, throw a runtime error such as anAssertionError
.
...
} catch (Exception e) {
assert false : "This exception should not happen";
}
...
} 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. |