c++的异常要比java的麻烦一点...
1.通常情况下,应该在异常处理器中使用引用参数而不是值参数,以防异常对象所包含的信息被切割掉,"..."能捕获任何异常一般放在最后,从而避免架空它后面的异常处理器。
2.异常是在运行时而不是在编译时被检测的,因此,编译时存在的大量信息在处理异常的时候是不存在的
3.如果没有任何一个层次的异常处理器能够捕获某种异常,一个特殊的库函数(terminate())会被自动调用让程序执行异常而退出,全局对象和静态对象的函数不会执行。
4.如果一个对象的构造在执行过程中抛出异常,那么析构函数就不会被调用,一般不要在析构函数里抛出异常
#include<iostream>
#include<vector>
#include<stdexcept>//std::out_of_range
using namespace std;
int main()
{
vector<int> v;
for(size_t i=0;i<10;i++)
v.push_back(i);
cout << "front:" << v.front() << endl;
cout << "back:" << v.back() << endl;
v.pop_back();
cout << "at[1]:" << v.at(1) << endl;
cout << "size:" << v.size() << endl;
try{
v.at(100);
}catch(std::out_of_range){
cout << "catch" << endl;
}
}
#include<iostream>
#include<exception>
using namespace std;
class B{};
class A{
public:
A(){};
void fun(int i)throw(char,int,bool,A,bad_exception){
switch(i){
case 0:
throw 'c';
break;
case 1:
throw 1;
break;
case 2:
throw true;
break;
case 3:
throw A();
break;
case 4:
throw 4.0;
break;
}
}
};
void myException(){
cout << "do not finish the program" << endl;
}
void myException2(){
throw;
}
int main()
{
set_unexpected(myException);
A a;
for(int i=0;i<5;i++){
try{
if(i==4)set_unexpected(myException2);//
a.fun(i);
}catch(char c){
cout << "char=" << c << endl;
}catch(int ii){
cout << "int=" << ii << endl;
}catch(bool b){
cout << "bool=" << b << endl;
}catch(A& a){
cout << "a" << endl;
}catch(bad_exception&){
cout << "cat a bad exception" << endl;
}
}
}
char=c
int=1
bool=1
a
cat a bad exception
获得式初始化,构造函数在抛出异常之前完成,析构函数也会在栈反解的时候被调用
#include<iostream>
using namespace std;
template<class T,int sz=1> class D{
T* p;
public:
class err{};
D(){
p = new T;
}
~D(){
delete p;
cout<<"~D()"<<endl;
}
};
class A{
public:
A(){cout<<"A()"<<endl;}
~A(){cout<<"~A()"<<endl;}
};
class B{
public:
// void* operator new(size_t){
// cout << "new B" <<endl;
// throw 3;
// }
// void operator delete[](void *p){
// cout << "delete B" << endl;
// delete[](p);
// }
B(){
cout<<"B()"<<endl;
throw 3;
}
~B(){cout<<"~B()"<<endl;}
};
class C{
D<A> a;
D<B> b;
public:
C(){
cout << "C()" <<endl;
}
~C(){
cout << "~C()" <<endl;
}
};
int main()
{
try{
C c;
}catch(...){
cout<<"catch" << endl;
}
}
A()
B()
~A()
~D()
catch