Junior — Middle
Can you explain what std::exception_ptr is in C++ and how it is used for exception handling?
sobes.tech AI
Answer from AI
std::exception_ptr is a smart pointer in C++ that stores information about an exception, allowing it to be preserved and rethrown later. This is useful for passing exceptions between threads or for deferred processing.
Key points:
- You can obtain an exception_ptr using std::current_exception() inside a catch block.
- You can rethrow the exception using std::rethrow_exception(exception_ptr).
Example:
#include <iostream>
#include <exception>
#include <thread>
void threadFunc(std::exception_ptr& eptr) {
try {
throw std::runtime_error("Error in thread");
} catch (...) {
eptr = std::current_exception(); // save the exception
}
}
int main() {
std::exception_ptr eptr;
std::thread t(threadFunc, std::ref(eptr));
t.join();
if (eptr) {
try {
std::rethrow_exception(eptr); // rethrow
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
}
return 0;
}
Thus, std::exception_ptr allows safe transfer of exceptions between contexts.