How To Use Propagating Exceptions In Modern C++?
Modern C++ has many features to aid multi-thread programming that allow applications to be faster and more responsive. The C++11 standard offers the possibility of moving an exception from one thread to another. This type of movement is called propagating exceptions, exception propagation; also known as rethrow exception in multi-threading. To do that, some modifications have been made to the header in C++ and there is a nullable pointer-like type std::exception_ptr. In this post, we explain std::exception_ptr and how to use the rethrow exception method in modern C++. What are propagating exceptions (exception propagation) in modern C++? The C++11 standard offers a nullable pointer-like type std::exception_ptr. The exception_ptr is used to refer to an exception and manages an exception object that has been thrown and captured with std::current_exception(). Here is how we can use both: std::exception_ptr e = std::current_exception(); In modern C++, a concurrency support library is designed to solve problems in multi-thread operations. This library includes built-in support for threads (std::thread), atomic operations (std::atomic), mutual exclusion (std::mutex), condition variables (std::condition_variable), and many other features. In addition to these useful features, std::exception_ptr is useful in exception handling between threads. They may be passed to another function, possibly to another thread function, so that the exception can be rethrown and handled in another thread with a catch clause. According to open-std, “An exception_ptr that refers to the currently handled exception or a copy of the currently handled exception, or a null exception_ptr if no exception is being handled. If the function needs to allocate memory and the attempt fails, it returns an exception_ptr that refers to an instance of bad_alloc. It is unspecified whether the return values of two successive calls to current_exception refer to the same exception.” The exception_ptr can be DefaultConstructible, CopyConstructible, Assignable and EqualityComparable. By default, it is constructed as a null pointer, doesn’t point to an exception, and operations from exception_ptr do not throw. Is there a simple example of how to use propagating exceptions in modern C++? Here is a simple example that outputs exceptions coming from a thread. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 std::mutex m; void throw_exception( std::exception_ptr e) { try { if (e) std::rethrow_exception(e); } catch(const std::exception& e) { m.lock(); std::cout
