Exceptions and Fibers

This lesson explains how to handle exceptions while using fibers.

We'll cover the following

Earlier, you saw how “an exception object that is thrown from a lower level function is transferred to the higher level functions one level at a time.” We also discussed how an uncaught exception “causes the program to finally exit the main() function.” The described behavior of the exception mechanism can also be achieved by the call stack.

Stack unwinding

Continuing with the first example in this chapter, if an exception is thrown inside bar(), first the frame of bar() would be removed from the call stack, then foo()'s, and finally main()'s. As functions are exited and their frames are removed from the call stack, the destructors of local variables are executed for their final operations. The process of leaving functions and executing destructors of local variables due to a thrown exception is called stack unwinding.

Since fibers have their own stack, an exception that is thrown during the execution of the fiber unwinds the fiber’s call stack, not its caller’s. If the exception is not caught, the fiber function terminates, and the fiber’s state becomes Fiber.State.TERM.

Although this may be the desired behavior in some cases, sometimes a fiber may need to communicate an error condition to its caller without losing its execution state. Fiber.yieldAndThrow allows a fiber to yield and immediately throw an exception in the caller’s context.

To see how it can be used, let’s enter invalid age data to the sign-on program:

Get hands-on with 1000+ tech skills courses.