Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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: -5

The 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: -5

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.