When an exception is thrown while already handling another exception, it's called a nested exception. This can lead to tricky situations and potential resource leaks if not handled carefully.
One strategy is to catch and handle the nested exception separately, and then continue handling the original exception:
#include <iostream>
#include <stdexcept>
void handleException() {
try {
throw std::runtime_error(
"Original exception");
} catch (const std::exception& e) {
std::cout << "Handling: "
<< e.what() << "\n";
try {
throw std::logic_error("Nested exception");
} catch (const std::exception& nested_e) {
std::cout << "Handling nested: "
<< nested_e.what() << "\n";
}
std::cout << "Continuing handling "
"original exception\n";
}
}
int main() {
handleException();
}
Handling: Original exception
Handling nested: Nested exception
Continuing handling original exception
Another approach is to capture the nested exception using std::current_exception()
, store it in a std::exception_ptr
, and then rethrow it after finishing handling the original exception:
#include <exception>
#include <iostream>
#include <stdexcept>
void handleException() {
std::exception_ptr nested_eptr;
try {
throw std::runtime_error(
"Original exception");
} catch (const std::exception& e) {
std::cout << "Handling: " << e.what() << "\n";
try {
throw std::logic_error("Nested exception");
} catch (...) {
nested_eptr = std::current_exception();
}
std::cout << "Continuing handling "
"original exception\n";
}
if (nested_eptr) {
std::rethrow_exception(nested_eptr);
}
}
int main() {
try {
handleException();
} catch (const std::exception& e) {
std::cout << "Caught rethrown nested "
"exception: " << e.what() << "\n";
}
}
Handling: Original exception
Continuing handling original exception
Caught rethrown nested exception: Nested exception
This ensures the nested exception isn't lost and can be handled at a higher level if needed.
Answers to questions are automatically generated and may not have been reviewed.
This lesson offers a comprehensive guide to storing and rethrowing exceptions