在C++程序中,错误处理通常通过以下几种方式进行:
-1或nullptr来表示错误。#include <iostream>
#include <cstdlib>
int main() {
int result = std::system("nonexistent_command");
if (result != 0) {
std::cerr << "Error executing command\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
try-catch块来捕获并处理这些异常。#include <iostream>
#include <stdexcept>
void mightFail() {
throw std::runtime_error("An error occurred");
}
int main() {
try {
mightFail();
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
assert宏用于在调试阶段检查不应该发生的情况。如果断言失败,程序将终止。#include <iostream>
#include <cassert>
int main() {
int x = -1;
assert(x >= 0 && "x should be non-negative");
return EXIT_SUCCESS;
}
#include <iostream>
#include <string>
class ErrorHandler {
public:
ErrorHandler(const std::string& msg) : message(msg) {}
void logError() const {
std::cerr << "Error: " << message << '\n';
}
private:
std::string message;
};
void riskyOperation() {
throw ErrorHandler("Something went wrong");
}
int main() {
try {
riskyOperation();
} catch (const ErrorHandler& e) {
e.logError();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
boost::system。#include <boost/system/error_code.hpp>
#include <iostream>
namespace fs = boost::filesystem;
int main() {
fs::path p("nonexistent_file.txt");
boost::system::error_code ec;
if (!fs::exists(p, ec)) {
std::cerr << "Error: " << ec.message() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
在实际编程中,可以根据具体情况选择合适的错误处理方式。通常,异常处理是最灵活和强大的方法,但也需要更多的注意来确保资源的正确管理(例如,使用RAII原则)。返回错误码和断言则更适合于简单的错误检查和资源受限的环境。