在 Ubuntu(Linux)下使用 C++ 处理异常,本质上使用的是 C++ 标准异常机制(try / catch / throw),和 Windows 没有本质区别,只是编译、运行环境不同。下面从基础用法 → 编译方法 → 常见实践 → Ubuntu 特有注意点给你讲清楚。
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
throw runtime_error("发生错误");
} catch (const exception& e) {
cerr << "捕获异常: " << e.what() << endl;
}
return 0;
}
<stdexcept>)#include <stdexcept>
| 类型 | 说明 |
|---|---|
runtime_error |
运行时错误 |
logic_error |
逻辑错误 |
out_of_range |
越界 |
invalid_argument |
参数非法 |
ios_base::failure |
IO 错误 |
示例:
throw out_of_range("index too big");
class MyException : public exception {
public:
const char* what() const noexcept override {
return "My custom exception";
}
};
使用:
throw MyException();
g++ main.cpp -o main
./main
✅ C++ 异常 默认开启,不需要额外参数
g++ -std=c++17 main.cpp -o main
int* p = nullptr;
*p = 10; // ❌ 段错误,不会进入 catch
✅ 段错误是 操作系统信号,不是 C++ 异常
✅ 无法通过 try/catch 捕获
可以处理信号(进阶):
#include <signal.h>
void handler(int) { exit(1); }
signal(SIGSEGV, handler);
系统调用一般返回 -1,用 errno:
#include <cerrno>
#include <cstring>
if (open("file", O_RDONLY) == -1) {
throw runtime_error(strerror(errno));
}
❗ 子线程异常不会传播到主线程
void thread_func() {
throw runtime_error("thread error"); // 直接 terminate
}
✅ 正确做法:
try {
thread_func();
} catch (...) {
// 捕获后传回主线程
}
class File {
public:
File(const char* name) { f = fopen(name, "r"); }
~File() { if (f) fclose(f); }
private:
FILE* f;
};
✅ 即使抛出异常,资源也会释放
catch (...) { } // ❌ 危险
ulimit -c unlimited
./main
生成 core 文件,用 gdb 分析
g++ -fno-exceptions main.cpp
❌ 会导致 throw 直接调用 terminate
✅ 掌握顺序:
如果你愿意,可以告诉我:
我可以给你更针对性的示例。