Rethrowing Exceptions and noexcept
What happens if I rethrow an exception in a noexcept function?
If a noexcept function throws an exception, whether directly or by rethrowing, it results in a call to std::terminate(), which by default, calls abort() and terminates the program.
#include <exception>
#include <iostream>
#include <stdexcept>
void rethrowException() noexcept {
try {
throw std::runtime_error(
"Original exception");
} catch (...) {
std::rethrow_exception(
std::current_exception());
}
}
int main() {
try {
rethrowException();
} catch (const std::exception& e) {
std::cout << "Caught exception: "
<< e.what() << "\n";
}
}Error: abort() has been calledIn this example, rethrowException() is marked noexcept, but it rethrows an exception. This will call std::terminate() and abort the program. The catch block in main() will never be reached.
It's important to ensure that noexcept functions do not throw exceptions, including through rethrowing. If a noexcept function needs to handle an exception, it should catch and handle it fully within the function without rethrowing.
Alternatively, if a function needs to rethrow exceptions, it should not be marked noexcept:
#include <exception>
#include <iostream>
#include <stdexcept>
void rethrowException() { // not noexcept
try {
throw std::runtime_error(
"Original exception");
} catch (...) {
std::rethrow_exception(
std::current_exception());
}
}
int main() {
try {
rethrowException();
} catch (const std::exception& e) {
std::cout << "Caught exception: "
<< e.what() << "\n";
}
}Caught exception: Original exceptionNow the exception is rethrown and caught in main() as expected.
Storing and Rethrowing Exceptions
This lesson offers a comprehensive guide to storing and rethrowing exceptions