CKTIS / PHP
Exception::getMessage — read an exception message
Read the text of a caught exception, distinguish it from the code and stack trace, and decide what belongs in a log versus a user-facing response.
Version: PHP 8.3; extension availability may vary
Syntax
final public function getMessage(): string
$e->getMessage()Exception::getMessage returns the message of an exception object as a string. It is a public instance method with no arguments, and final means subclasses cannot override it. The :: identifies the class in the method name; to call it, use -> on the object: $e->getMessage(). In PHP 8.3, calling it on new \Exception() with no message returns the empty string ''.
catch (\Exception $e) catches \Exception objects and their subclasses, but not \Error objects. To handle both hierarchies, use catch (\Throwable $e): the shared interface also exposes getMessage(). This does not catch ordinary warnings that are not thrown as objects. The leading \ selects the global name even inside a namespace.
getMessage() returns neither the code nor the stack trace; use getCode() and getTrace() for those. It does not include the previous exception's message either. Use getPrevious() to retrieve the previous object, and check for null before calling getMessage() on it.
Do not branch on the wording of a message. Use an exception type or a code with documented meaning instead. In production, do not show raw exception messages to users: they can contain paths or sensitive data. Show a safe message and log only appropriately sanitized diagnostic details.
Examples
<?php
try {
$cause = new \Exception('Invalid row format');
throw new \Exception('Import failed', previous: $cause);
} catch (\Exception $e) {
echo $e->getMessage(), "\n";
$previous = $e->getPrevious();
if ($previous !== null) {
echo $previous->getMessage(), "\n";
}
}Result
Import failed Invalid row format
The first line is the caught exception's message. The second appears only because the code retrieves the previous object and calls `getMessage()` on it separately.
Related lessons
- PHP · Lesson 41 · Advanced · Version: 2
- PHP · Lesson 67 · Advanced · Version: 2
- PHP · Lesson 68 · Advanced · Version: 2
- PHP · Lesson 69 · Advanced · Version: 2
- PHP · Lesson 70 · Advanced · Version: 2
- PHP · Lesson 75 · Advanced · Version: 2
- PHP · Lesson 82 · Advanced · Version: 2
- PHP · Lesson 20 · Intermediate · Version: 3