How do I map error codes to exceptions and vice versa?

In C++, mapping error codes to exceptions and vice versa is a common practice for handling errors more effectively. Error codes are often used in functions to signal specific failure conditions, while exceptions provide a way to throw errors that can be caught and handled using try-catch blocks. Below is an example illustrating how to implement this mapping.

#include <iostream> #include <stdexcept> // Define custom exception class class CustomException : public std::runtime_error { public: explicit CustomException(const std::string &message) : std::runtime_error(message) {} }; // Function that returns an error code int riskyOperation() { // Simulating an error return -1; // Error code } // Function to map error codes to exceptions void execute() { int errorCode = riskyOperation(); if (errorCode < 0) { throw CustomException("An error occurred: error code " + std::to_string(errorCode)); } } int main() { try { execute(); } catch (const CustomException &e) { std::cerr << "Caught an exception: " << e.what() << std::endl; } return 0; }

error codes exceptions C++ custom exception error handling