C++ 异常处理:类型、示例及最佳实践
在 C++ 中,异常是程序在运行时遇到错误或异常情况时引发的事件。异常机制提供了一种处理错误的方法,使得我们可以在程序中捕获并处理这些异常,从而保证程序的正常执行。
C++ 中的异常类型包括以下几种:
- std::exception: 是所有标准异常类的基类。它提供了一个通用的接口,可以通过继承它来创建自定义的异常类。
例子:
try {
throw std::exception();
} catch (const std::exception& e) {
// 处理异常
}
- std::bad_alloc: 当内存分配失败时抛出。通常在使用
new操作符分配内存时发生。
例子:
try {
int* arr = new int[1000000000000000000];
} catch (const std::bad_alloc& e) {
// 处理内存分配失败的异常
}
- std::runtime_error: 在运行时检测到的错误引发的异常。通常是由程序逻辑错误导致的。
例子:
try {
int x = 10;
int y = 0;
if (y == 0) {
throw std::runtime_error('除数不能为零');
}
int result = x / y;
} catch (const std::runtime_error& e) {
// 处理除以零的异常
}
- std::logic_error: 在编译时可以检测到的错误引发的异常。通常是由于程序设计错误导致的。
例子:
try {
int x = 10;
int y = 11;
if (y > 10) {
throw std::logic_error('y 的值不能大于 10');
}
} catch (const std::logic_error& e) {
// 处理 y 大于 10 的异常
}
- std::out_of_range: 当使用超出有效范围的索引访问容器元素时引发的异常。
例子:
try {
std::vector<int> vec = {1, 2, 3};
int value = vec.at(10);
} catch (const std::out_of_range& e) {
// 处理索引越界的异常
}
这些只是 C++ 中异常的一些常见类型,还有其他类型的异常。使用异常时需要小心,只在必要的情况下使用,以避免异常滥用和性能损失。同时,在捕获异常时,应该根据具体情况选择合适的异常类型并进行适当的处理。
原文地址: https://www.cveoy.top/t/topic/qizl 著作权归作者所有。请勿转载和采集!