C++通过try-catch和throw实现异常处理,支持多种类型异常捕获及标准异常类使用,推荐用std::exception派生类自定义异常,合理使用可提升程序健壮性。

在C++中,异常处理是一种用于应对程序运行时错误的机制,它允许程序在出现问题时优雅地恢复或退出,而不是直接崩溃。C++通过 try-catch 语句实现异常处理,配合 throw 关键字抛出异常,形成完整的异常处理流程。
异常处理的基本结构:try-catch
try-catch 是C++中处理异常的核心语法结构。代码中可能发生异常的部分放在 try 块中,一旦 throw 抛出异常,程序会立即跳转到匹配的 catch 块进行处理。
示例:#includeusing namespace std; int main() { try { int age = -5; if (age < 0) { throw "Age cannot be negative!"; } cout << "Age is: " << age << endl; } catch (const char* msg) { cout << "Exception caught: " << msg << endl; } return 0; }
上面代码中,当检测到年龄为负数时,使用 throw 抛出一个字符串异常,程序跳转到 catch 块并输出提示信息。
catch 多种类型的异常
异常可以是任意类型,如 int、string、自定义类等。C++支持多个 catch 块来捕获不同类型的异常,系统会按顺序匹配第一个能处理该异常类型的块。
立即学习“C++免费学习笔记(深入)”;
try {
throw 42; // 抛出整型异常
}
catch (int e) {
cout << "Caught int exception: " << e << endl;
}
catch (const string& e) {
cout << "Caught string exception: " << e << endl;
}
catch (...) {
cout << "Caught unknown exception" << endl;
}
其中 catch(...) 表示捕获所有未被前面 catch 块处理的异常,常用于兜底处理。
使用标准异常类
C++标准库提供了丰富的异常类,定义在
常见标准异常包括:
- std::runtime_error:运行时错误
- std::invalid_argument:无效参数
- std::out_of_range:越界访问
- std::bad_alloc:内存分配失败
#include#include using namespace std; double divide(int a, int b) { if (b == 0) { throw runtime_error("Division by zero!"); } return (double)a / b; }
int main() { try { double result = divide(10, 0); cout << "Result: " << result << endl; } catch (const runtime_error& e) { cout << "Error: " << e.what() << endl; } return 0; }
使用 what() 方法可以获取异常的描述信息,便于调试和用户提示。
自定义异常类
对于特定业务逻辑,可以定义自己的异常类,通常继承自 std::exception 或其派生类。
class MyException : public runtime_error {
public:
MyException(const string& msg) : runtime_error(msg) {}
};
// 使用方式
try {
throw MyException("Something went wrong in my module.");
}
catch (const MyException& e) {
cout << "Custom exception: " << e.what() << endl;
}
这样既能复用标准接口,又能提供更具体的错误上下文。
基本上就这些。合理使用 try-catch 能让程序更健壮,但不应滥用异常来控制正常流程。异常适用于“异常”情况,比如资源不可用、输入非法等,而不是替代返回值或条件判断。











