coro/genexcept.hpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <iostream>
#include <exception>
#include <generator>

std::generator<int> coroWithException()
{
  std::cout << "\t** coro(): yield 1" << std::endl;
  co_yield 1;                                       // SUSPEND with 1

  std::cout << "\t** coro(): yield 2" << std::endl;
  co_yield 2;                                       // SUSPEND with 2

  std::cout << "\t** coro(): THROW" << std::endl;
  throw std::runtime_error{"error in coroutine"};   // THROW exception
  std::cout << "\t** coro(): not reached" << std::endl;
}