Throwing Exceptions From Coroutines | iboB

submited by
Style Pass
2024-10-06 12:30:06

So, you want to throw an exception from a coroutine. The wisdom says that in your promise_type you have to implement unhandled_exception, store the exception in std::exception_ptr, and then rethrow it or handle it otherwise when it’s appropriate. This is a decent approach in many situations. However for synchronous coroutines (think generators) I’d say it’s overcomplicated to the point of being stupid.

…and make my exception somebody else’s problem. However the standard didn’t allow this initially. Not expclicitly at least. The coroutine state after such a move was simply not specified. Is it suspended? What does it mean when final_suspend is not called? Apparently no one had thought of this trivial use case. Now, the complex ones, sure, but the standard committee is beyond trivialities…

So, someone finaly figured out that it is stupid to require the overly complicated code for something as trivial as propagating the exception, made a defect report, and it was even reflected in the standard… in 2022, but at least it was retroactive, which means that it applies to C++20 even though it came out later. C++20 conforming compilers must implement it. For example it is available in GCC 11.4.

Leave a Comment