gpt4 book ai didi

c++ - 使用标准异常类

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:36 26 4
gpt4 key购买 nike

我正在尝试使用 C++ 中的标准异常类,例如:

#include <iostream>
#include <exception>
using namespace std;
int main(){
int a[6]={12,3,2,4,5,6};
int n=6;
try{
cout<<a[6]<<" ";

}
catch(std::exception & exc)
{
cout<<exc.what();

}

return 0;
}

但是它没有向我显示错误 - “超出索引”,而是抛出一个运行时错误,说“变量 a 未初始化”,为什么?我已经将它声明为一个数组并对其进行了初始化。请给我一些建议,为什么会这样?

最佳答案

正在访问 a[6]是未定义的行为,因为 a 的唯一有效索引是0 .. 5 .

你不应该期待 a[6]执行任何边界检查,更不用说在越界数组访问时抛出 C++ 异常了。

如果你想要自动边界检查,制作a进入std::vector<int>并使用 a.at(index)访问其元素。

关于c++ - 使用标准异常类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7662356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com