Java - Assert

> Procedural Languages > Java

1 - About

The asert keyword in Java is a inline assertion.

3 - Syntax

It's first role is to reduce the following code:

if(variable == null) {
    throw new RuntimeException("variable is null");
}

by this:

assert variable != null : "variable is null";

If the assertion fails, you get a java.lang.AssertionError:

java.lang.AssertionError: variable  is null
Advertising

4 - Other assertion example

4.1 - requireNonNull

this.session = java.util.Objects.requireNonNull(session, "session is null");
lang/java/assert.txt · Last modified: 2019/11/11 10:09 by gerardnico