C++中异常处理通过try-catch结构捕获并处理运行时错误,避免程序崩溃。try块包含可能出错的代码,catch块捕获特定或通用异常,推荐使用引用传递防止对象切片。标准异常如logic_error、runtime_error定义在<stdexcept>中,可提升兼容性;throw用于抛出异常,支持自定义异常类。最佳实践包括:用const T&捕获、避免在析构函数抛异常、结合RAII管理资源,确保异常安全。

在C++中,异常处理是一种用于应对程序运行时错误的机制。通过 try-catch 结构,程序可以在出现异常时进行捕获并做出相应处理,避免程序崩溃或产生不可预知的行为。
异常的基本结构:try 和 catch
try-catch 是 C++ 异常处理的核心语法。代码中可能出错的部分放在 try 块中,一旦抛出异常,程序会立即跳转到匹配的 catch 块进行处理。
基本语法如下:
try {
// 可能抛出异常的代码
} catch (异常类型1 e) {
// 处理特定类型的异常
} catch (异常类型2& e) {
// 推荐使用引用传递,避免拷贝和对象切片
} catch (...) {
// 捕获所有类型的异常(通配符)
}
示例:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
using namespace std;
<p>int main() {
try {
throw runtime_error("发生了一个错误!");
} catch (const runtime_error& e) {
cout << "捕获异常:" << e.what() << endl;
}
return 0;
}
</font></p><H3>常见异常类型与标准异常类</H3><p>C++ 提供了标准库中的异常类,定义在 <stdexcept> 头文件中。常用的包括:</p><ul><li><strong>logic_error</strong>:逻辑错误,如无效参数(invalid_argument)、超出范围(out_of_range)</li><li><strong>runtime_error</strong>:运行时错误,如文件打开失败、计算溢出</li><li><strong>bad_alloc</strong>:内存分配失败(new 操作符抛出)</li><li><strong>bad_cast</strong>:dynamic_cast 类型转换失败</li></ul><p>使用标准异常可以提高代码可读性和兼容性。例如:</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/1600" title="GentleAI"><img
src="https://img.php.cn/upload/ai_manual/000/969/633/68b6dbb8eec69167.png" alt="GentleAI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/1600" title="GentleAI">GentleAI</a>
<p>GentleAI是一个高效的AI工作平台,为普通人提供智能计算、简单易用的界面和专业技术支持。让人工智能服务每一个人。</p>
</div>
<a href="/ai/1600" title="GentleAI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><font face="Courier New"><pre class="brush:php;toolbar:false;">
#include <stdexcept>
#include <vector>
int main() {
vector<int> v(5);
try {
v.at(10) = 1; // 抛出 out_of_range
} catch (const out_of_range& e) {
cout << "越界错误:" << e.what() << endl;
}
return 0;
}
如何抛出异常(throw)
使用 throw 关键字可以手动抛出异常。它可以抛出任意类型的对象,但推荐使用标准异常或自定义异常类。
自定义异常示例:
class MyException {
public:
const char* what() const {
return "这是一个自定义异常";
}
};
<p>void riskyFunction() {
throw MyException();
}</p><p>int main() {
try {
riskyFunction();
} catch (const MyException& e) {
cout << e.what() << endl;
}
return 0;
}</p>异常安全与最佳实践
合理使用异常处理能提升程序健壮性,但也需注意以下几点:
- 尽量使用引用捕获异常(catch(const T&)),避免对象切片和不必要的拷贝
- 不要忽略异常,至少应记录日志或提示用户
- 避免在析构函数中抛出异常,可能导致程序终止
- RAII(资源获取即初始化)配合异常使用,确保资源正确释放(如智能指针)
- 谨慎使用 catch(...),除非你确实要处理所有异常
示例:使用 RAII 管理资源
#include <memory>
void func() {
auto ptr = make_shared<int>(42); // 自动管理内存
if (someError)
throw runtime_error("出错了");
// 即使抛出异常,ptr 也会自动释放
}
基本上就这些。C++ 的异常机制虽然不如 Java 或 Python 那样强制,但在大型项目中合理使用 try-catch 能显著提升代码的容错能力。关键是理解什么时候该抛出、什么时候该捕获,并结合 RAII 做好资源管理。










