Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Throwable.getMessage()

Returns the message text of an exception.

Available since: Java 1.0

Syntax

public String getMessage()

Return value

StringThe exception text, or `null` if none was given.

Examples

The message and the string form:

void main() {
    try {
        throw new IllegalArgumentException("Price must be positive");
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
        IO.println(e);
    }
    IO.println(new RuntimeException().getMessage());
}

Output:

Price must be positive
java.lang.IllegalArgumentException: Price must be positive
null

Notes

getMessage() returns only the text, while toString() (and printing e) gives the class name and the text. For an exception created without a message getMessage() returns null, so in logs it is handier to print the e object itself.

See also

Related recipes

In the tutorial

  • try, catch and finally — Handling exceptions in Java — the try and catch blocks, several catch blocks, multi-catch, finally and throwing exceptions with throw.

Thanks for reading!

Donate to the site — we work hard for you.