assert
A check of an internal program condition. Disabled by default, enabled with the -ea option.
Available since: Java 1.4
Syntax
assert condition; / assert condition : message;Examples
Without the -ea option the check does not run at all:
void main() {
int age = -5;
assert age >= 0 : "age must not be negative: " + age;
IO.println("Age: " + age);
}Output:
Age: -5The same code run as java -ea Main.java:
void main() {
int age = -5;
assert age >= 0 : "age must not be negative: " + age;
IO.println("Age: " + age);
}Output:
Exception in thread "main" java.lang.AssertionError: age must not be negative: -5Notes
assert catches programmer mistakes during development and tests: "this list is already sorted", "null cannot get here". Do not use it to validate input or arguments of public methods — in production the check is off; throw IllegalArgumentException or call Objects.requireNonNull() instead. The condition must have no side effects: without -ea it is not evaluated.
See also
- throw — Throws an exception and stops the method.
- IllegalArgumentException — Signals that a method received an invalid argument.
- Objects.requireNonNull() — Checks that a value is not null and throws NullPointerException with a clear message right away.
In the tutorial
- What exceptions are — Exceptions in Java — how a program reports an error, how to read a stack trace, common exceptions and the Throwable hierarchy.