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 called

In 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 exception

Now 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Capturing Exceptions in a Different Thread
How can I capture an exception thrown in one thread and handle it in a different thread?
Handling Nested Exceptions
What is a good strategy for handling exceptions that are thrown while already handling another exception?
Using std::exception_ptr Across DLL Boundaries
Can I use std::exception_ptr to transfer exceptions across DLL boundaries?
Capturing and Rethrowing Custom Exceptions
Can I use std::exception_ptr to capture and rethrow custom exceptions?
std::exception_ptr and Memory Management
Are there any memory management considerations when using std::exception_ptr?
Performance Considerations with std::exception_ptr
What are the performance implications of using std::exception_ptr?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant