c++++标准库异常类体系定义在<stdexcept>中,继承自std::exception,用于报告运行错误。1. std::exception是基类,提供虚函数what()描述异常信息,不可直接抛出。2. 异常分为逻辑错误(如invalid_argument、domain_error、length_error、out_of_range)和运行时错误(如runtime_error、range_error、overflow_error、underflow_error)。3. 逻辑错误由程序逻辑引起,运行时错误与外部环境相关。4. 抛出异常建议使用具体子类对象,捕获时用常量引用。5. 自定义异常应继承标准类,保持一致性。掌握这些有助于编写健壮、易维护的代码。

C++标准库提供了一套异常类体系,主要定义在
<stdexcept>
std::exception

std::exception
what()
你不能直接抛出
std::exception
立即学习“C++免费学习笔记(深入)”;

try {
throw std::runtime_error("Something went wrong");
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
}上面的例子展示了如何通过引用捕获所有从
std::exception
what()
C++标准库中常见的异常类分为两大类:逻辑错误和运行时错误。

这类异常表示可以在程序编写阶段避免的错误,通常是由于错误的输入或逻辑判断引起的。
std::logic_error
std::invalid_argument
std::domain_error
std::length_error
std::out_of_range
举个例子:
std::vector<int> v = {1, 2, 3};
try {
int x = v.at(5); // 抛出 out_of_range 异常
} catch (const std::out_of_range& e) {
std::cerr << "Out of range error: " << e.what() << std::endl;
}这类异常表示无法在编译期预知的问题,通常与外部环境有关。
std::runtime_error
std::range_error
std::overflow_error
std::underflow_error
例如:
double compute_ratio(int a, int b) {
if (b == 0)
throw std::runtime_error("Division by zero");
return static_cast<double>(a) / b;
}虽然这里用了基类,但也可以根据具体情况使用更具体的派生类。
logic_error
runtime_error
std::exception
std::runtime_error
std::exception
常见做法:
std::invalid_argument
std::out_of_range
std::runtime_error
基本上就这些。掌握好这些标准异常类,能帮助你写出更清晰、更安全的 C++ 代码。
以上就是C++标准库异常类有哪些 详解std exception及其派生类的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号