转载:http://blog.youkuaiyun.com/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异常。