C++通过try、catch、throw实现异常处理,配合标准库异常类和自定义异常类提升程序健壮性,结合RAII确保资源安全。

在C++中,异常处理是通过 try、catch 和 throw 三个关键字来实现的。它允许程序在运行时检测并响应错误情况,避免程序崩溃,同时提升代码的健壮性和可维护性。
基本语法结构
一个典型的异常处理流程如下:
try {
// 可能抛出异常的代码
throw exception_type();
}
catch (exception_type& e) {
// 捕获并处理特定类型的异常
}
当 try 块中的代码执行 throw 语句时,程序会查找匹配的 catch 块。如果找到,就执行对应的处理逻辑。
使用标准异常类
C++ 标准库提供了丰富的异常类,定义在
立即学习“C++免费学习笔记(深入)”;
- std::runtime_error:运行时错误
- std::invalid_argument:无效参数
- std::out_of_range:越界访问
- std::bad_alloc:内存分配失败(new 操作符抛出)
示例:
#include#include int main() { try { throw std::invalid_argument("参数不合法"); } catch (const std::invalid_argument& e) { std::cout << "捕获到 invalid_argument: " << e.what() << std::endl; } return 0; }
多类型异常捕获
一个 try 块可以有多个 catch 块,用于处理不同类型的异常。匹配顺序是从上到下,因此更具体的异常应放在前面。
try {
// ...
if (error1) throw std::runtime_error("运行错误");
if (error2) throw std::out_of_range("索引越界");
}
catch (const std::out_of_range& e) {
std::cout << "越界错误: " << e.what() << std::endl;
}
catch (const std::runtime_error& e) {
std::cout << "运行时错误: " << e.what() << std::endl;
}
catch (...) {
std::cout << "未知异常" << std::endl;
}
注意:catch(...) 能捕获所有异常,通常作为兜底处理,但无法获取异常信息。
自定义异常类
你可以定义自己的异常类,继承自 std::exception 或其子类,重写 what() 方法提供错误信息。
class MyException : public std::exception {
public:
const char* what() const noexcept override {
return "这是自定义异常";
}
};
// 使用
try {
throw MyException();
}
catch (const MyException& e) {
std::cout << e.what() << std::endl;
}
异常安全与资源管理
异常可能中断正常执行流,导致资源泄漏。推荐使用 RAII(资源获取即初始化)技术,如智能指针、锁包装器等,确保异常发生时资源仍能正确释放。
例如,使用 std::unique_ptr 而非裸指针,避免内存泄漏。
基本上就这些。合理使用 try-catch,结合标准或自定义异常类型,能让 C++ 程序更稳定地应对运行时错误。











