在C++中,std::exception位于<exception>头文件,是标准库异常体系的基类。通过它我们可以以统一的方式处理各类运行时错误,避免程序因未捕获的异常直接终止。合理使用标准异常类有助于提高代码的健壮性和可维护性。

std::exception的基本结构
std::exception定义了一个虚函数what(),用于返回描述错误的字符串。标准库中的很多异常(如std::runtime_error、std::logic_error)都继承自它。我们通常通过引用捕获,以防止对象切片。
捕获标准异常的例子
下面代码演示了如何抛出并捕获std::runtime_error,它是std::exception的派生类:
#include <iostream>
#include <stdexcept>
int divide(int a, int b) {
if (b == 0) {
// 抛出标准异常派生类
throw std::runtime_error("除数不能为0");
}
return a / b;
}
int main() {
try {
int result = divide(10, 0);
std::cout << "结果:" << result << std::endl;
} catch (const std::exception& e) {
// 通过基类引用捕获,调用what获取信息
std::cout << "捕获异常:" << e.what() << std::endl;
}
return 0;
}
自定义异常类
当标准异常描述不够用时,可以从std::exception派生自己的异常类,重写what()方法:
#include <exception>
#include <string>
class MyError : public std::exception {
private:
std::string msg;
public:
explicit MyError(const std::string& m) : msg(m) {}
const char* what() const noexcept override {
return msg.c_str();
}
};
使用建议
- 尽量按引用捕获异常,如catch(const std::exception& e)。
- 在底层抛出具体标准异常,在高层统一处理std::exception。
- 不要在析构函数中抛出异常,以免造成程序终止。
掌握std::exception的使用,是编写符合现代C++规范的错误处理代码的基础。
C++std_exception异常处理修改时间:2026-07-30 22:54:22