C++通过try-catch机制处理异常,保障程序健壮性;标准异常分为逻辑异常(如invalid_argument、out_of_range)和运行时异常(如runtime_error、overflow_error),可自定义异常类并结合RAII确保资源安全。

在C++中,异常处理是程序健壮性的重要保障。通过 try-catch 机制,可以有效捕获运行时异常和逻辑异常,避免程序崩溃并提供合理的错误响应。
C++标准库定义了两类主要异常,均继承自 std::exception:
将可能抛出异常的代码放在 try 块中,用 catch 捕获并处理。建议按派生类到基类的顺序捕获,避免覆盖。
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3};
try {
// 逻辑异常示例:访问越界
std::cout << vec.at(10) << std::endl;
// 运行时异常示例:手动抛出
throw std::runtime_error("运行时错误:文件无法打开");
}
catch (const std::out_of_range& e) {
std::cerr << "逻辑错误:" << e.what() << std::endl;
}
catch (const std::runtime_error& e) {
std::cerr << "运行时错误:" << e.what() << std::endl;
}
catch (const std::exception& e) {
std::cerr << "其他标准异常:" << e.what() << std::endl;
}
catch (...) {
std::cerr << "未知异常被捕获" << std::endl;
}
return 0;
}
对于特定业务逻辑,可继承 std::exception 或其子类定义异常类型。同时注意异常安全:确保资源正确释放,避免内存泄漏。
立即学习“C++免费学习笔记(深入)”;
class MyException : public std::runtime_error {
public:
MyException() : std::runtime_error("自定义运行时错误") {}
};
// 使用示例
try {
throw MyException();
}
catch (const MyException& e) {
std::cerr << e.what() << std::endl;
}
配合智能指针(如 std::unique_ptr)和 RAII 技术,可有效提升异常安全性。
基本上就这些。掌握标准异常分类、正确使用 try-catch 结构、合理设计自定义异常,就能有效应对C++中的运行时和逻辑异常问题。以上就是C++如何捕获运行时和逻辑异常的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号