Learn how to solve the "__toString() must not throw an exception" error in PHP.

Last week, I needed to work on an old project using Symfony 1.4. I decided to install composer so I was able to install many PHP libraries instead of relying on single Sf 1.4 plugins. One of the libraries that I needed was Kint, the PHP fancy debugger to display some data of some rows in the database. These rows were brought by Doctrine 1, however for some reason, I get a constant error namely that the SomeTableClass threw the "error: __toString() must not throw an exception" exception.

The error wasn't of course in the Kint library, but a problem with the classes of the entity that i wanted to display. Kint casts the magic __toString method on any class that you want to debug, however the class was causing an exception as the property didn't exist at all, so you will need to add a try-catch statement on the magic method on the class where you have the error:

class YourClassThatThrowsAnException {
    // ..
    // Original Code of your class
    // ..

    public function __toString() {
        try {
            // Note that the property needs to exist
            // on the class, or therefore the exception
            // will be thrown
            return (string) $this->getName();
        } catch (Exception $exception) {
            // Optionally you can var_dump the error message to see why the exception is being thrown !
            var_dump($exception->getMessage());
            return '';
        }
    }
}

Note that as we said in the comment, you will need to return a property that exists and always a string value, or another exception will be thrown. Besides it's pretty useful if you are sure that the property exists, to add a var_dump line in the catch block so you can see the message generated by PHP to see what's failing. We return an empty string to override the error when the property doesn't exist, so I was able to dump anyway with Kint.

Happy coding !


Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Become a more social person

Sponsors