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
nullNotes
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
- Throwable.printStackTrace() — Prints the exception and the chain of calls that led to it to the error stream.
- Throwable.getCause() — Returns the original exception wrapped by the current one.
- Exception — The base class of exceptions a program can catch and handle.
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.