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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?