在 Ubuntu(Linux)下用 C++ 处理异常,核心还是 C++ 标准异常机制,和 Windows 差别不大,但有一些平台相关的注意事项。下面从基础到实践系统讲一下。
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::runtime_error("something wrong");
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
#include <stdexcept>)std::runtime_errorstd::logic_errorstd::out_of_rangestd::invalid_argumentclass MyException : public std::exception {
public:
const char* what() const noexcept override {
return "MyException occurred";
}
};
g++ main.cpp -o main
./main
g++ -fexceptions main.cpp
若使用
-fno-exceptions,则不能使用 try/catch
C++ try/catch 无法捕获:
#include <csignal>
#include <iostream>
void handler(int sig) {
std::cerr << "Signal: " << sig << std::endl;
exit(1);
}
int main() {
signal(SIGSEGV, handler);
}
⚠️ 信号处理中不要抛出异常
std::terminatethrow 1; // 没有 catch
程序直接 abort,生成 core dump(若开启)
#include <exception>
void my_terminate() {
std::cerr << "terminate called" << std::endl;
abort();
}
int main() {
std::set_terminate(my_terminate);
}
gdb ./main
run
bt
catch throw
catch catch
✅ 使用 const std::exception&
✅ 异常只用于“异常流程”
✅ 不要在析构函数中抛异常
✅ 多线程中异常不跨线程传播
std::thread t([]{
throw std::runtime_error("thread error"); // 会导致 terminate
});
✅ 正确方式:
try {
t.join();
} catch (...) {}
或在 thread 内部捕获
如果你愿意,我可以:
你现在是写 服务端 / 嵌入式 / 桌面程序?