Fiber Throws Where The Fiber Is

../_images/fiber-throw-suspension.png

Fiber is the generator’s sibling that nobody writes tips about, so here is one.

$fiber->throw($exception) does not throw in the caller’s own scope. It resumes the suspended fiber and raises the exception exactly at the Fiber::suspend() call that paused it, as if that call itself had thrown.

That means an ordinary try/catch written around the suspend() call inside the fiber’s body will catch it, with no special API needed on the fiber’s side.

Also note that Fiber::getCurrent() returns null outside of any fiber, and that starting an already-started fiber throws a FiberError, not a silent no-op.

See Also

PHP Features