您的位置:首页 > 编程语言 > C语言/C++

c++ out_of_range

2016-05-12 11:44 701 查看
转载:http://blog.csdn.net/wxqian25/article/details/14230523

对std::out_of_range抛出异常进行处理 ,头文件stdexcept

#include <iostream>

#include <vector>

#include <stdexcept>

using namespace std;

int main() {

vector <int> a;

a.push_back(1);

try {

a.at(1);

}

catch (std::out_of_range &exc) {

std::cerr << exc.what() << " Line:" << __LINE__ << " File:" << __FILE__ << endl;

}

return EXIT_SUCCESS;

}

这样就能知道在第几行和哪个文件中了。
说明编辑
C++异常类,继承自logic_error,logic_error的父类是exception。属于运行时错误,如果使用了一个超出有效范围的值,就会抛出此异常。也就是一般常说的越界访问。定义在命名空间std中。
使用时须包含头文件 #include<stdexcept>

out_of_range例子

编辑
// out_of_range example
#include<iostream>
#include<stdexcept>
#include<vector>
using namespace std;//或者用其他方式包含using std::logic_error;和using std::out_of_range;
int main (void)
{
vector<int> myvector(10);
try
{
myvector.at(20)=100; // vector::at throws an out-of-range
}
catch (out_of_range& oor)
{
cerr << "Out of Range error: " << oor.what() << endl;
}
getchar();
return 0;
}
myvector只有10个元素,所以myvector.at(20)就会抛出out_of_range异常。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: