Method %s::__toString() must not throw an exception, caught %s: %s

Description

Until PHP 8.0, __toString could not throw exception, and would end up with this error. In PHP 8.0, it is now possible.

Example

<?php

class X {
    function __toString() {
        throw new \Exception('error');
    }

    function foo() {
        throw new \Exception('error');
    }

}

?>

Literal Examples

  • Method X::__toString() must not throw an exception, caught Exception: error

Solutions

  • Upgrade to PHP 8.0.

  • Store the error in another property, and check the property in another method, after the call to __toString.