温馨提示×

ubuntu c++怎样处理异常

小樊
40
2026-09-08 09:55:25
栏目: 编程语言

在 Ubuntu(Linux)下用 C++ 处理异常,核心还是 C++ 标准异常机制,和 Windows 差别不大,但有一些平台相关的注意事项。下面从基础到实践系统讲一下。


一、C++ 标准异常处理(通用)

1. 基本语法

#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;
}

2. 常见标准异常(#include <stdexcept>

  • std::runtime_error
  • std::logic_error
  • std::out_of_range
  • std::invalid_argument

3. 自定义异常

class MyException : public std::exception {
public:
    const char* what() const noexcept override {
        return "MyException occurred";
    }
};

二、Ubuntu / Linux 下的编译

1. 使用 g++

g++ main.cpp -o main
./main

2. 开启异常(默认开启)

g++ -fexceptions main.cpp

若使用 -fno-exceptions,则不能使用 try/catch


三、信号与系统级异常(Linux 特有)

C++ try/catch 无法捕获

  • 段错误(SIGSEGV)
  • 浮点异常(SIGFPE)
  • 总线错误(SIGBUS)

1. 使用 signal 捕获

#include <csignal>
#include <iostream>

void handler(int sig) {
    std::cerr << "Signal: " << sig << std::endl;
    exit(1);
}

int main() {
    signal(SIGSEGV, handler);
}

⚠️ 信号处理中不要抛出异常


四、未捕获异常(Ubuntu 行为)

1. std::terminate

throw 1; // 没有 catch

程序直接 abort,生成 core dump(若开启)

2. 设置全局终止函数

#include <exception>

void my_terminate() {
    std::cerr << "terminate called" << std::endl;
    abort();
}

int main() {
    std::set_terminate(my_terminate);
}

五、调试异常(Ubuntu 推荐)

1. 使用 gdb

gdb ./main
run
bt

2. 捕获所有异常(gdb)

catch throw
catch catch

六、最佳实践(Linux C++)

✅ 使用 const std::exception&
✅ 异常只用于“异常流程”
✅ 不要在析构函数中抛异常
✅ 多线程中异常不跨线程传播


七、多线程中的异常

std::thread t([]{
    throw std::runtime_error("thread error"); // 会导致 terminate
});

✅ 正确方式:

try {
    t.join();
} catch (...) {}

或在 thread 内部捕获


如果你愿意,我可以:

  • 给你一个 Ubuntu 下的完整异常示例项目
  • C++17 / C++20 异常新特性
  • 或对比 C++ 异常 vs Linux 错误码(errno)

你现在是写 服务端 / 嵌入式 / 桌面程序

0