在Linux环境中的C++程序中,错误处理通常包括以下几个方面:
#include <iostream>
#include <stdexcept>
int main() {
try {
// 代码逻辑
throw std::runtime_error("发生错误");
} catch (const std::exception& e) {
std::cerr << "捕获到异常: " << e.what() << std::endl;
}
return 0;
}
#include <iostream>
#include <cerrno>
int main() {
FILE* file = fopen("nonexistent_file.txt", "r");
if (file == nullptr) {
std::cerr << "无法打开文件: " << std::strerror(errno) << std::endl;
return -1;
}
// 文件操作
fclose(file);
return 0;
}
#include <csignal>
#include <iostream>
void signal_handler(int signal) {
std::cerr << "捕获到信号: " << signal << std::endl;
// 清理资源、关闭文件等
exit(signal);
}
int main() {
std::signal(SIGSEGV, signal_handler); // 捕获段错误信号
std::signal(SIGABRT, signal_handler); // 捕获断言失败信号
// 程序逻辑
int* ptr = nullptr;
*ptr = 42; // 触发段错误
return 0;
}
#include <iostream>
#include <spdlog/spdlog.h>
int main() {
try {
// 代码逻辑
throw std::runtime_error("发生错误");
} catch (const std::exception& e) {
spdlog::error("捕获到异常: {}", e.what());
}
return 0;
}
assert宏来检查程序中的假设条件,如果条件不满足,则终止程序并显示错误信息。#include <iostream>
#include <cassert>
int main() {
int a = 5;
assert(a == 10 && "a的值应该是10");
return 0;
}
在实际编程中,可以根据需要选择合适的错误处理方法,甚至可以组合使用多种方法来提高程序的健壮性。