c++++标准库中的函数和stl操作在出错时会抛出异常,常见的异常类型包括:1. std::logic_error(逻辑错误);2. std::runtime_error(运行时错误),如std::invalid_argument、std::out_of_range、std::length_error;3. std::bad_alloc(内存分配失败);4. 与rtti相关的异常如std::bad_cast。stl容器操作中,push_back、emplace_back、resize、reserve可能抛出bad_alloc;at()方法访问越界抛出out_of_range;map的at()在键不存在时也抛出out_of_range;string的substr在pos越界时抛出out_of_range;stoi等转换函数在输入无效时抛出invalid_argument或out_of_range。new操作符在内存不足时抛出bad_alloc,但可用nothrow避免抛出。流操作默认不抛异常,但可通过设置掩码启用,如failbit触发std::ios_base::failure异常。了解这些有助于提高程序健壮性并合理使用异常处理机制。

C++标准库中的很多函数和STL操作在遇到错误时会抛出异常。了解这些异常行为,有助于我们在编写程序时更好地进行异常处理,提高程序的健壮性。

C++标准库定义了一组通用的异常类,它们都继承自
std::exception

std::logic_error
std::runtime_error
std::invalid_argument
std::out_of_range
at()
std::length_error
std::bad_alloc
std::bad_cast
bad_typeid
这些是我们在使用 STL 和标准库函数时最常碰到的异常类型。
立即学习“C++免费学习笔记(深入)”;
不同的 STL 容器在执行某些操作时可能会抛出异常,具体行为取决于操作本身和底层实现。

std::bad_alloc
bad_alloc
std::out_of_range
例如:
std::vector<int> v(5); v.at(10) = 42; // 抛出 std::out_of_range 异常
at()
std::out_of_range
substr(pos, len)
out_of_range
stoi / stof / stol
invalid_argument
out_of_range
默认情况下,
new
std::bad_alloc
nothrow
int* p = new (std::nothrow) int[1000000000]; // 分配失败返回 nullptr
if (!p) {
// 处理内存不足的情况
}注意:并不是所有平台或编译器都支持
nothrow
流对象(如
ifstream
istringstream
std::ifstream file("data.txt");
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
file >> value;
} catch (...) {
// 处理读取失败
}failbit
badbit
eofbit
开启异常后,流操作失败就会抛出
std::ios_base::failure
基本上就这些常见情况。C++标准库中大多数函数都会在文档中标注是否会抛出异常,建议查阅官方文档确认细节。异常机制虽然强大,但也要合理使用,避免过度依赖 try-catch 来处理流程控制。
以上就是C++标准库函数会抛出哪些异常 常见STL操作的异常行为说明的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号