Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

lang.AssertionError: practical reference

lang.AssertionError: practical reference: AssertionError is thrown when an enabled assert statement fails and should not replace validation of external input.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.lang.AssertionError

AssertionError is thrown when an enabled assert statement fails and should not replace validation of external input.

Use AssertionError through assert for internal development-time invariants, never for validating external input.

Assertions are disabled by default, so their condition may not execute. Catching Error normally hides a program defect.

The detail expression is evaluated only after condition failure and may produce any value, including null.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        try { throw new AssertionError("failed"); } catch (AssertionError error) { System.out.println(error.getMessage()); }
    }
}

Result

failed

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources