1、越界,可以结合stdexcept使用out_of_range类进行针对性异常处理;
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <exception>
using namespace std;
int main () throw (exception)
{
vector<int> v(5);
fill(v.begin(),v.end(),1);
copy(v.begin(),v.end(),
ostream_iterator<int>(cout," "));
cout << endl;
try
{
for ( int i=0; i<10; i++ )
cout << v.at(i) << " ";
cout << endl;
}
catch( exception& e )
{
cout << endl << "Exception: "
<< e.what() << endl;
}
cout << "End of program" << endl;
return 0;
}
运行结果:
// 1 1 1 1 1
// 1 1 1 1 1
// Exception: vector::_M_range_check
// End of program
2、无效参数,可以结合stdexcept使用invalid_argument类进行针对性异常处理;
#include <iostream>
#include <exception>
#include <bitset>
using namespace std;
int main (void)
{
try
{
//如果用包含非0或1的字符串初始化bitset对象,它将抛出无效参数异常
tset<5> mybitset (string("01234"));
}
catch (exception& ia)
{
cerr << "Invalid argument: " << ia.what() << endl;
}
return 0;
}
运行结果:
Invalid argument: bitset::_M_copy_from_ptr
3、长度异常,可以结合stdexcept使用length_error类进行针对性异常处理;
#include <iostream>
#include <exception>
#include <vector>
using namespace std;
int main(void)
{
try
{
// 如果调整或申请容器的大小大于容器的最大容量,将抛出长度异常
vector<int> myvector;
myvector.resize(myvector.max_size()+1);
}
catch(length_error& le)
{
cerr << "Length error: " << le.what() << endl;
}
return 0;
}
4、分配失败,可以结合stdexcept使用bad_alloc类进行针对性异常处理;
#include <iostream>
#include <exception>
using namespace std;
int main () throw ( exception )
{
const unsigned long SIZE = 500000000;
char *ptr[10];
try
{
for ( int counter = 0; counter < 10; counter++ )
{
ptr[counter] = new char[SIZE];
cout << "Memory for ptr[" << counter
<< "] is allocated" << endl;
}
}
catch (exception &e)
{
cout << "Exception: ";
cout << e.what() << endl;
return 1;
}
for ( int i = 0; i < 10; i++ )
delete [] ptr[i];
cout << "End" << endl;
return 0;
}
运行结果:
// Memory for ptr[0] is allocated
// Memory for ptr[1] is allocated
// Memory for ptr[2] is allocated
// Memory for ptr[3] is allocated
// Memory for ptr[4] is allocated
// Exception: bad_alloc
除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。



