在C++程序中,错误处理通常通过以下几种方式来实现:
int divide(int a, int b, int &result) { if (b == 0) { return -1; // 错误码:除数为零 } result = a / b; return 0; // 成功 } try、catch和throw关键字来捕获和处理异常。例如:#include <stdexcept> int divide(int a, int b) { if (b == 0) { throw std::runtime_error("除数为零"); } return a / b; } int main() { int result; try { result = divide(10, 0); } catch (const std::runtime_error &e) { std::cerr << "错误:" << e.what() << std::endl; } return 0; } #include <iostream> #include <cerrno> #include <cstring> #define CHECK_FUNCTION_CALL(func) \ if ((func) == -1) { \ std::cerr << "错误:" << std::strerror(errno) << std::endl; \ return 1; \ } int main() { int fd = open("nonexistent_file.txt", O_RDONLY); CHECK_FUNCTION_CALL(fd); close(fd); return 0; } boost::system::error_code和boost::system::error_condition。在实际编程中,可以根据程序的需求和风格选择合适的错误处理方法。通常情况下,异常处理适用于处理不可预见的错误,而返回错误码和错误处理宏适用于处理可预见的错误。