__toString() and Exceptions

Prior to PHP 7.4, raising an exception during the execution of a __toString() method was not allowed. This was due to the technical limitation that not all parts of the PHP runtime’s codebase were able to deal with exceptions when an automatic object-to-string conversion needs to be performed.

class C
{
    public function __toString(): string
    {
        throw new Exception;
    }
}

print new C;

Executing the code shown above with PHP 7.3 and earlier resulted in the error shown below:

Fatal error: Method C::__toString() must not throw an exception,
caught Exception: in ...

Executing the same code with PHP 7.4 and later prints the output shown below:

Fatal error: Uncaught Exception in ...