c++ out_of_range

来源:互联网 发布:动物知乎 编辑:程序博客网 时间:2024/05/19 19:15

转载:http://blog.csdn.net/wxqian25/article/details/14230523

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


  1. #include <iostream>  
  2. #include <vector>  
  3. #include <stdexcept>  
  4. using namespace std;  
  5. int main() {  
  6.     vector <int> a;  
  7.     a.push_back(1);  
  8.     try {  
  9.         a.at(1);  
  10.     }  
  11.     catch (std::out_of_range &exc) {  
  12.         std::cerr << exc.what() << " Line:" << __LINE__ << " File:" << __FILE__ << endl;  
  13.     }  
  14.     return EXIT_SUCCESS;  
  15. }   

 这样就能知道在第几行和哪个文件中了。

说明编辑

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异常。

0 0
原创粉丝点击