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 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异常。
对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异常。
相关文章推荐
- HDU 2516-取石子游戏(斐波那契博弈)
- c++中冒号(:)和双冒号(::)的用法
- c语言之内存的申请malloc() 和释放free()
- RSA算法C语言实现
- C/C++中typedef的使用
- C语言中malloc()和calloc()c函数用法
- 在C++中使用TinyXML2解析xml
- C++ 指针
- C++11的新特性
- google test 轻松编写C++单元测试
- C++类(Class)总结
- Visual C++中 #include "stdafx.h" 头文件的用法
- C语言指针变量的概念
- 使用jni实现在C语言中打印log信息
- iOS OC语言: Block底层实现原理
- C语言实现去除字符串中空格的简单实例
- C++ 拷贝构造函数 赋值构造函数
- 发现一个c++ vector sort的bug
- error C2664: 'CreateThread' : cannot convert parameter 3 from 'int (void *)'
- C++ 文件类型分析