简体   繁体   中英

Exceptions don't bubble through instances in PHP?

I was getting an error about an exception thrown in a __toString() method in a class of mine, even though there was a try...catch() in there. I did some tracking down and it turns out an object within my instance was throwing an exception in its __toString() , which meant that it wasn't being caught by the containing class' catch!

I wrote some test code as a demonstration:

class test {
      public function __toString() {
        try {
            $b = new b();
            echo (string)$b;
        } catch (exception $e) {
            return (string)$e;
        }
    }
}

class b {
    public function __toString() {
        throw new Exception ("test");
    }
}

$test = new test();

echo $test;

I had thought that exceptions always "bubbled up" through the code until they were caught or made it all the way out.

Is there any workaround for this? The instance within my class is from a library; I don't know if I can maintainably modify it to have a catch in its own __toString() .

Per PHP's __toString() section in the magic methods docs :

Warning

You cannot throw an exception from within a __toString() method. Doing so will result in a fatal error.

When executing the code snippet you gave you get a message that says the same thing:

PHP Fatal error: Method b::__toString() must not throw an exception

There's a feature request here to support this, which states that in current state of things it would be hard to implement.

Having said all that, the proper way to fix this is to submit a patch to your upstream library to not throw exceptions from that method.

If that's not possible, the workaround for you is instead of:

echo (string)$b;

write

echo $b->__toString();

In which case you can catch the exception as you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM