// 示例代码:解决常见的C++运行时错误
#include <iostream>
#include <vector>
void example1() {
// 1. 空指针引用导致的运行时错误
int* ptr = nullptr;
try {
if (ptr == nullptr) {
throw std::runtime_error("指针为空,不能解引用");
}
*ptr = 10; // 这里会抛出异常
} catch (const std::exception& e) {
std::cerr << "捕获到异常: " << e.what() << '\n';
}
}
void example2() {
// 2. 数组越界访问导致的运行时错误
std::vector<int> vec = {1, 2, 3};
try {
if (vec.size() <= 3) {
throw std::out_of_range("数组越界");
}
vec.at(5) = 10; // 这里会抛出异常
} catch (const std::exception& e) {
std::cerr << "捕获到异常: " << e.what() << '\n';
}
}
void example3() {
// 3. 动态内存分配失败导致的运行时错误
int* largeArray = new (std::nothrow) int[1000000000];
if (largeArray == nullptr) {
std::cerr << "内存分配失败\n";
} else {
delete[] largeArray;
}
}
int main() {
example1();
example2();
example3();
return 0;
}
空指针引用:
example1
函数中,我们尝试解引用一个空指针 nullptr
。为了避免程序崩溃,我们在解引用之前检查指针是否为 nullptr
,并抛出一个 std::runtime_error
异常。使用 try-catch
块可以捕获并处理这个异常。数组越界访问:
example2
函数中,我们尝试访问超出 std::vector
范围的元素。为了避免未定义行为,我们使用 vec.at(index)
方法,它会在索引超出范围时抛出 std::out_of_range
异常。同样,使用 try-catch
块来捕获和处理异常。动态内存分配失败:
example3
函数中,我们尝试分配一个非常大的数组。为了避免程序崩溃,我们使用 new (std::nothrow)
来分配内存,并检查返回的指针是否为 nullptr
。如果分配失败,输出相应的错误信息。通过这些示例,我们可以看到如何在 C++ 中处理常见的运行时错误,并确保程序的健壮性和稳定性。
上一篇:c和c++区别
下一篇:c++入门
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站