Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Throwable.getMessage() — read an exception’s message

`getMessage()` returns an exception’s detail message, or `null` if there is no message. Calling the method does not print anything.

Version: Java SE 21

Syntax

public String getMessage()

Throwable.getMessage names the method declared in java.lang.Throwable; the parentheses in Throwable.getMessage() show that it takes no arguments. It is an instance method, not a static method: call it on an object, for example e.getMessage() inside a catch block.

The method returns the object's own detail message as a String. In the example, IllegalArgumentException(String) sets the message, whereas the no-argument constructor creates an exception with no message, so getMessage() returns null. A null result is not the empty string "". If you need text, check the result and use a fallback when it is null.

getMessage() does not print anything or return the cause object or a stack trace. getCause() returns the cause or null, while printStackTrace() prints the stack trace, by default to standard error. By default, getLocalizedMessage() returns the same result as getMessage(), but a subclass can override it to provide locale-specific text.

Treat the message as diagnostic text, not as a stable error code. For program logic, use exception types or documented error codes instead of parsing the wording. Do not show raw messages to users if they may reveal sensitive information.

Examples

public class Main {
    public static void main(String[] args) {
        try {
            throw new IllegalArgumentException("Validation failed.");
        } catch (IllegalArgumentException e) {
            System.out.println(messageOrFallback(e));
        }

        System.out.println(messageOrFallback(new IllegalArgumentException()));
    }

    private static String messageOrFallback(Throwable error) {
        String message = error.getMessage();
        return message == null ? "No detail message." : message;
    }
}

Result

Validation failed.
No detail message.

The first line comes from the message passed to the caught exception’s constructor. The second is the fallback: the no-argument constructor sets no message, so `getMessage()` returns `null`.

Related lessons

  • Java · Lesson 50 · Basic · Version: 2
  • Java · Lesson 51 · Basic · Version: 2
  • Java · Lesson 52 · Basic · Version: 2
  • Java · Lesson 53 · Basic · Version: 2
  • Java · Lesson 50 · Intermediate · Version: 2

Sources