异常
1、捕捉异常
void A(int i)
{
try {
B(i);
} catch (int j)
{
cout<<"catch int exception "<<j<<endl;
} catch (double d)
{
cout<<"catch double exception "<<d<<endl;
} catch (MyException &e)
{
e.what();
} catch (...){ //其他异常
cout<<"catch other exception "<<endl;
}
}
A捕捉B
2、B抛出异常(B调用C)
void C(int i) throw(int, double)
{
int a = 1;
double b= 1.2;
float c = 1.3;
if (i == 0)
{
cout<<"In C, it is OK"<<endl;
}
else if (i == 1)
throw a;
else if (i == 2)
throw b;
else if (i == 3)
throw c;
else if (i == 4)
throw MyException();
else if (i == 5)
throw MySubException();
}
注意:C里面声明一些,没申明的会出问题(系统默认处理函数处理)。
3、默认函数(意料之外的异常)
#include <iostream>
#include <exception>
using namespace std;
void my_unexpected_func () cout<<"catch unexpected exception"<<endl;
void B(void) throw (int,double)
throw 'a'; /* 本应该throw int或double, 但是现在throw char, 这是个意外的异常 */
int main (void)
set_unexpected (my_unexpected_func);
try
B();
catch (int)
cout<<"catch exception int"<<endl;
catch (...)
/* 拥捉其他被声明的异常 */
cout<<"catch other expected exception"<<endl;
return 0;
对于意料之外的异常,会执行2个函数:
"unexpected"函数(可以自己提供), "terminate"函数(可以自己提供)
#include <exception>
void my_terminate_func () cout<<"my_terminate_func"<<endl;
set_terminate(my_terminate_func);
"unexpected"函数用来处理声明之外的异常
“terminate"函数用来处理"catch分支未捉到异常”
例子:
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
class MyException {
public:
virtual void what(void) { cout<<"This is MyException"<<endl; }
};
class MySubException : public MyException{
public:
void what(void) { cout<<"This is MySubException"<<endl; }
};
void C(int i) throw(int, double)
{
int a = 1;
double b= 1.2;
float c = 1.3;
if (i == 0)
{
cout<<"In C, it is OK"<<endl;
}
else if (i == 1)
throw a;
else if (i == 2)
throw b;
else if (i == 3)
throw c;
else if (i == 4)
throw MyException();
else if (i == 5)
throw MySubException();
}
void B(int i)
{
cout<<"call C ..."<<endl;
C(i);
cout<<"After call C"<<endl;
}
void A(int i)
{
try {
B(i);
} catch (int j)
{
cout<<"catch int exception "<<j<<endl;
} catch (MyException &e)
{
e.what();
}
}
void my_unexpected_func()
{
cout<<"my_unexpected_func"<<endl;
}
void my_terminate_func () { cout<<"my_terminate_func"<<endl; }
int main(int argc, char **argv)
{
int i;
set_unexpected (my_unexpected_func);
set_terminate(my_terminate_func);
if (argc != 2)
{
cout<<"Usage: "<<endl;
cout<<argv[0]<<" <0|1|2|3>"<<endl;
return -1;
}
i = strtoul(argv[1], NULL, 0);
A(i);
return 0;
}