Exceptions: throw, try and catch

Rethrowing Exceptions

What is rethrowing an exception in C++, and when is it useful?

Abstract art representing computer programming

Rethrowing an exception in C++ refers to the process of catching an exception and then throwing it again without modifying it. This is useful when you want to perform some action or logging before propagating the exception to the next level of exception handling.

To rethrow an exception, you simply use the throw keyword without any argument inside a catch block. Here's an example:

#include <iostream>

void foo() {
  try {
    // Some code that may throw an exception
    throw std::runtime_error("Something went wrong");
  } catch (const std::exception& ex) {
    std::cout << "Caught exception in foo: "
      << ex.what() << std::endl;
    throw;  // Rethrow the exception
  }
}

int main() {
  try {
    foo();
  } catch (const std::exception& ex) {
    std::cout << "Caught exception in main: "
      << ex.what() << std::endl;
  }
}
Caught exception in foo: Something went wrong
Caught exception in main: Something went wrong

In this example, the foo function catches an exception of type std::exception, logs a message, and then rethrows the exception using the throw keyword without any argument. The exception is then caught in the main function, where it is handled and another message is logged.

Rethrowing exceptions can be useful in the following scenarios:

Logging and error reporting

  • When an exception is caught, you may want to log some information about the exception or perform some error reporting before propagating the exception further.
  • Rethrowing the exception allows you to handle the exception at multiple levels while still preserving the original exception information.

Modifying exception information

  • Sometimes, you may want to catch an exception, modify some information or add additional context, and then rethrow the exception with the updated information.
  • This can be done by catching the exception, modifying it, and then rethrowing it.

Handling exceptions at different levels

  • Rethrowing exceptions allows you to handle exceptions at different levels of the call stack.
  • You can catch an exception at a lower level, perform some actions, and then rethrow it to be handled by higher-level code.

Here's an example that demonstrates modifying exception information before rethrowing:

#include <iostream>
#include <stdexcept>

class CustomException
  : public std::runtime_error {
 public:
  CustomException(
    const std::string& message, int errorCode)
      : std::runtime_error(message),
        errorCode_(errorCode) {}

  int getErrorCode() const {
    return errorCode_;
  }

 private:
  int errorCode_;
};

void processData(int data) {
  try {
    if (data < 0) {
      throw CustomException("Invalid data", -1);
    }
    // Process the data
  } catch (const CustomException& ex) {
    std::cout << "Caught CustomException in "
      "processData: " << ex.what() << std::endl;

    throw CustomException(
      ex.what(), ex.getErrorCode() + 100);
  }
}

int main() {
  try {
    processData(-5);
  } catch (const CustomException& ex) {
    std::cout
      << "Caught CustomException in main: "
      << ex.what()
      << ", Error Code: " << ex.getErrorCode();
  }
}
Caught CustomException in processData: Invalid data
Caught CustomException in main: Invalid data, Error Code: 99

In this example, we define a custom exception class CustomException that inherits from std::runtime_error and adds an error code. Inside the processData function, if an exception of type CustomException is caught, we log a message and then rethrow the exception with an updated error code.

When the exception is caught in the main function, it includes the modified error code, providing additional context about the exception.

Rethrowing exceptions allows you to handle and modify exceptions at different levels of the call stack while preserving the original exception information. However, it's important to use rethrowing judiciously and ensure that the exception is eventually handled and not propagated indefinitely.

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

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