How to safely handle PHP “__toString() must not throw an exception”

Because there is no safe way to handle an exception thrown during __toString the easiest workaround for this is to catch all exceptions thrown and return either an empty string or null.

Since any invocation of __toString will expect a string back, it is a graceful way to handle any under-the-hood errors if you’re using __toString as a shortcut to echo out objects.

4 comments

Leave a Reply to Mathieu Cancel reply

  • This is how I handle exceptions in __toString() :
    If an exception handler has been set (set_exception_handler), I will call that handler manually. In this case you can still log your eception, be notified, or whatever.
    If no exception handler has been set, I like to print the exception in html comments.

    public function __toString()
    {
    try {
    $str = $this->render();
    } catch (\Exception $exception) {
    $previousHandler = set_exception_handler(function () {});
    restore_error_handler();
    if (!$previousHandler) {
    $str = “getMessage().””;
    $str .= $exception->getTraceAsString();
    $str .= “\n–>”;

    return $str;
    } else {
    call_user_func($previousHandler, $exception);
    }
    die;
    }

    return $str;
    }

    • That’s a fair point, but the logger itself may then throw an exception which you cannot handle properly or have to handle silently; it’s probably best to avoid this magic method and handle string transformation explicitly to avoid this compromise