Storing and Rethrowing Exceptions

Rethrowing Exceptions and noexcept

What happens if I rethrow an exception in a noexcept function?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved