W3docs

getMessage()

Learn how the PHP Exception::getMessage() method retrieves the error message from a caught exception, with runnable examples, gotchas, and best practices.

Introduction

PHP's exception handling lets you separate the code that detects a problem from the code that responds to it. When something goes wrong, you throw an exception object that travels up the call stack until a matching catch block handles it. That object carries details about what happened — and the most commonly used of those details is the human-readable error message.

This chapter covers Exception::getMessage(), the method that returns that message string. You will learn what it returns, how it differs from the other "getter" methods on the exception object, common pitfalls, and how to use it for user-facing errors, logging, and debugging.

What getMessage() returns

getMessage() returns the message string that was passed as the first argument to the exception's constructor. PHP stores that string on the exception object the moment the exception is created, and getMessage() simply reads it back.

<?php
$e = new Exception("Something went wrong");
echo $e->getMessage(); // Something went wrong

Two facts worth remembering:

  • It takes no arguments and always returns a string.
  • If no message was passed to the constructor, it returns an empty string (""), not null.
<?php
$e = new Exception();      // no message
var_dump($e->getMessage()); // string(0) ""

getMessage() is defined on the base Exception class (and on Error), so it is available on every built-in and custom exception — RuntimeException, InvalidArgumentException, TypeError, and any class that extends them.

Syntax

final public Exception::getMessage(): string

The method is final, which means subclasses cannot override it — the message you pass to new Exception("...") is exactly what you get back.

Basic usage

To read a message, catch the exception in a try/catch block. The try block holds code that might fail; the catch block runs only if an exception is thrown.

<?php

function divide($a, $b) {
    if ($b === 0) {
        throw new InvalidArgumentException("Cannot divide by zero.");
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage();
}
?>

Output:

Caught: Cannot divide by zero.

InvalidArgumentException extends Exception, so the catch (Exception $e) block still catches it, and getMessage() returns the custom string we passed when throwing.

Practical use cases

Logging errors

A common pattern is to write the message to a log so you can investigate failures later. Pair getMessage() with getCode(), getFile(), and getLine() for richer log entries.

<?php
try {
    throw new RuntimeException("Database connection failed");
} catch (RuntimeException $e) {
    $entry = sprintf("[%s] %s", date("Y-m-d"), $e->getMessage());
    echo $entry;
}
?>

Output (date will vary):

[2026-06-21] Database connection failed

Showing a safe message to the user

Exception messages often contain technical detail. Use getMessage() for your logs, but show users a generic message in production so you do not leak internals such as file paths or SQL.

<?php
try {
    throw new Exception("SQLSTATE[28000]: Invalid password for user 'root'");
} catch (Exception $e) {
    error_log($e->getMessage());          // full detail goes to the log
    echo "Sorry, something went wrong.";  // safe message for the user
}
?>

getMessage() vs. the other exception getters

getMessage() is one of several read-only methods on an exception object. Knowing what each returns helps you pick the right one:

MethodReturns
getMessage()The message string passed to the constructor
getCode()The integer (or string) error code
getFile()The file where the exception was created
getLine()The line number where it was created
getTrace()The stack trace as an array
getPrevious()The previous exception in a chain, if any

If you want everything at once for debugging, casting the exception to a string (via __toString()) gives a formatted dump that already includes the message, file, line, and trace.

Gotchas

  • Empty message, not null. As shown above, a message-less exception returns "". Code like if ($e->getMessage()) will treat that as falsy — guard for it if an empty message is meaningful in your domain.
  • getMessage() is final. You cannot override it to transform the text. To customize what callers see, pass the desired string to the constructor (often via parent::__construct($message) in a custom exception class).
  • fopen() does not throw by default. Many PHP functions emit warnings and return false instead of throwing. In the file example below we check the return value and throw manually; functions like these will not populate getMessage() on their own unless you convert the warning into an exception (for example with set_error_handler()).

Full example

<?php

try {
    // fopen() returns false and emits a warning on failure rather than throwing
    $file = @fopen("does-not-exist.txt", "r");
    if (!$file) {
        throw new Exception("File not found");
    }
} catch (Exception $e) {
    echo "Error message: " . $e->getMessage();
}
?>

Output:

Error message: File not found

Here we open a file, detect failure by checking fopen()'s return value, and throw an Exception with a custom message. getMessage() then retrieves that string so we can display or log it. For guaranteed cleanup regardless of success or failure, you would add a finally block.

Conclusion

Exception::getMessage() returns the error message stored on a caught exception — the string you passed to the constructor, or an empty string if none was given. It is the simplest and most-used exception getter, ideal for logging, debugging, and producing user-facing feedback. Combine it with the other getters such as getCode() and getTrace() for complete error reports, and review PHP's overall exception handling model to use it effectively.

Practice

Practice
What does the getMessage() function in PHP do?
What does the getMessage() function in PHP do?
Was this page helpful?