C++通过try-catch机制处理异常,保障程序健壮性;标准异常分为逻辑异常(如invalid_argument、out_of_range)和运行时异常(如runtime_error、overflow_error),可自定义异常类并结合RAII确保资源安全。

在C++中,异常处理是程序健壮性的重要保障。通过 try-catch 机制,可以有效捕获运行时异常和逻辑异常,避免程序崩溃并提供合理的错误响应。
常见异常类型分类
C++标准库定义了两类主要异常,均继承自 std::exception:
-
逻辑异常:表示程序逻辑错误,如调用无效参数、越界访问等,通常在运行前可检测。常见类型包括:
- std::invalid_argument:参数不符合要求
- std::out_of_range:访问超出有效范围
- std::length_error:容器长度超出限制
-
运行时异常:表示运行过程中发生的不可预测错误,如除零、资源访问失败等。常见类型包括:
- std::runtime_error:通用运行时错误
- std::overflow_error:数值运算溢出
- std::range_error:结果超出表示范围
使用 try-catch 捕获异常
将可能抛出异常的代码放在 try 块中,用 catch 捕获并处理。建议按派生类到基类的顺序捕获,避免覆盖。
#include#include #include int main() { std::vector vec = {1, 2, 3}; try { // 逻辑异常示例:访问越界 std::cout << vec.at(10) << std::endl; // 运行时异常示例:手动抛出 throw std::runtime_error("运行时错误:文件无法打开"); } catch (const std::out_of_range& e) { std::cerr << "逻辑错误:" << e.what() << std::endl; } catch (const std::runtime_error& e) { std::cerr << "运行时错误:" << e.what() << std::endl; } catch (const std::exception& e) { std::cerr << "其他标准异常:" << e.what() << std::endl; } catch (...) { std::cerr << "未知异常被捕获" << std::endl; } return 0; }
自定义异常与异常安全
对于特定业务逻辑,可继承 std::exception 或其子类定义异常类型。同时注意异常安全:确保资源正确释放,避免内存泄漏。
立即学习“C++免费学习笔记(深入)”;
class MyException : public std::runtime_error {
public:
MyException() : std::runtime_error("自定义运行时错误") {}
};
// 使用示例
try {
throw MyException();
}
catch (const MyException& e) {
std::cerr << e.what() << std::endl;
}
配合智能指针(如 std::unique_ptr)和 RAII 技术,可有效提升异常安全性。
基本上就这些。掌握标准异常分类、正确使用 try-catch 结构、合理设计自定义异常,就能有效应对C++中的运行时和逻辑异常问题。










