Capturing and Rethrowing Custom Exceptions
Can I use std::exception_ptr
to capture and rethrow custom exceptions?
Yes, std::exception_ptr
can be used to capture and rethrow any type of exception, including custom exception types.
Here's an example that demonstrates this:
#include <exception>
#include <iostream>
#include <string>
class CustomException : public std::exception {
public:
explicit CustomException(
const std::string& what) : m_what(what) {}
const char* what() const noexcept override {
return m_what.c_str();
}
private:
std::string m_what;
};
void throwCustomException() {
throw CustomException(
"This is a custom exception");
}
std::exception_ptr captureException() {
try {
throwCustomException();
} catch (...) {
return std::current_exception();
}
return nullptr;
}
void rethrowException(std::exception_ptr eptr) {
try {
if (eptr) {
std::rethrow_exception(eptr);
}
} catch (const CustomException& e) {
std::cout << "Caught CustomException: "
<< e.what() << "\n";
} catch (const std::exception& e) {
std::cout << "Caught std::exception: "
<< e.what() << "\n";
}
}
int main() {
std::exception_ptr eptr = captureException();
rethrowException(eptr);
}
Caught CustomException: This is a custom exception
In this example:
- We define a custom exception class
CustomException
that derives fromstd::exception
. - The function
throwCustomException()
throws aCustomException
. - The function
captureException()
callsthrowCustomException()
, catches the exception, and captures it into astd::exception_ptr
usingstd::current_exception()
. - The
main()
function callscaptureException()
to get thestd::exception_ptr
, and then passes it torethrowException()
. rethrowException()
rethrows the exception usingstd::rethrow_exception()
. It then catches the rethrown exception, first trying to catchCustomException
, and thenstd::exception
.
This demonstrates that std::exception_ptr
can indeed capture and rethrow custom exception types. The custom exception can be caught and handled as expected when it's rethrown.
This capability is particularly useful when you need to transport exceptions through interfaces that don't know about your custom exception types, such as between layers of a complex system or across DLL boundaries.
Storing and Rethrowing Exceptions
This lesson offers a comprehensive guide to storing and rethrowing exceptions