c++++ 中用于异常处理的 stl 函数有:std::exception:异常的基础类std::bad_alloc:内存分配失败std::bad_cast:无效转换std::bad_typeid:无效类型 idstd::bad_array_new_length:无效数组长度std::overflow_error:算术运算溢出std::range_error:索引超范围或范围值无效

C++ 函数具有哪些 STL 函数可用于异常处理?
异常处理:
异常处理是处理异常情况的技术,如内存分配错误、除零错误等。
STL 异常处理函数:
立即学习“C++免费学习笔记(深入)”;
标准模板库 (STL) 提供了几个函数,可用于处理 C++ 中的异常:
std::exception:表示异常的基础类。std::bad_alloc:由内存分配失败引发。std::bad_cast:由无效转换引发。std::bad_typeid:由无效类型 ID 引发。std::bad_array_new_length:由 new[] 运算符分配的数组的无效长度引发。std::overflow_error:由算术运算溢出引发。std::range_error:由超出范围的索引或其他无效范围值引发。实战案例:
以下代码展示了如何使用 STL 函数处理异常:
#include <iostream>
#include <stdexcept>
void divide(int a, int b)
{
try {
int result = a / b;
std::cout << "Result: " << result << std::endl;
}
catch (const std::bad_alloc& e) {
std::cerr << "Memory allocation error: " << e.what() << std::endl;
}
catch (const std::overflow_error& e) {
std::cerr << "Arithmetic overflow error: " << e.what() << std::endl;
}
catch (const std::range_error& e) {
std::cerr << "Range error: " << e.what() << std::endl;
}
catch (const std::invalid_argument& e) {
std::cerr << "Invalid argument error: " << e.what() << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Unhandled exception: " << e.what() << std::endl;
}
}
int main()
{
try {
divide(10, 0);
}
catch (const std::overflow_error& e) {
std::cerr << "Caught division by zero" << std::endl;
}
return 0;
}在此示例中,divide() 函数使用 try-catch 块来处理可能会引发的异常。如果发生异常,它会根据异常类型打印相应的错误消息。
以上就是C++ 函数具有哪些 STL 函数可用于异常处理?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号