1 抛出异常和捕捉异常
代码清单 3.3.1
#include <iostream>using namespace std;void C(){throw 1;}void B(){C();}void A(){try{B();}catch (int i){cout<<"catch error"<<i<< endl;}}int main(int argc, char **argv){A();return 0;}
运行结果
catch error1
即嵌套的调用中可以选择抛出一个异常,该异常会被最顶层的函数直接获得
2 处理未知的异常
代码清单3.3.2
#include <iostream>
#include <stdlib.h>
using namespace std;
void C(int i)
{
int a = 1;
double b = 1.2;
float c = 1.3;
switch(i)
{
case 0:
cout << "C: OK" << endl;
break;
case 1:
throw a;
break;
case 2:
throw b;
break;
case 3:
throw c;
break;
default:break;
}
}
void B(int i)
{
cout << "B 1: " << endl;
C(i);
cout << "B 2: " << endl;
}
void A(int i)
{
try{
B(i);
}catch (int j)
{
cout<<"catch error"<<i<< endl;
}
}
int main(int argc, char **argv)
{
int i;
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;
}
运行结果:
solen@ubuntu:~/cpp$ ./try 1 B 1: catch error1 solen@ubuntu:~/cpp$ ./try 0 B 1: C: OK B 2: solen@ubuntu:~/cpp$ ./try 2 B 1: terminate called after throwing an instance of ‘double’ Aborted (core dumped) solen@ubuntu:~/cpp$ ./try 3 B 1: terminate called after throwing an instance of ‘float’ Aborted (core dumped)\
可见,如果没有throw出一个预期的数据类型,会引起代码崩溃。
处理方法
catch所有的类型
void A(int i)
{
try{
B(i);
}catch (int j)
{
cout<<"catch error"<<i<< endl;
}
catch (double k)
{
cout<<"catch error"<<k<< endl;
}
catch (float m)
{
cout<<"catch error"<<m<< endl;
}
}
处理方法2
void A(int i)
{
try{
B(i);
}catch (int j)
{
cout<<"catch error"<<i<< endl;
}
catch (double k)
{
cout<<"catch error"<<k<< endl;
}
catch (...)
{
cout<<"catch error"<< endl;
}
}
3 抛出类的实例
class myException
{
public:
void what(void)
{
cout << "myException" << endl;
}
};
void C(int i)
{
int a = 1;
double b = 1.2;
float c = 1.3;
switch(i)
{
case 0:
cout << "C: OK" << endl;
break;
case 1:
throw a;
break;
case 2:
throw b;
break;
case 3:
throw c;
break;
case 4:
throw myException();
default:break;
}
}
...
catch (class myException &e)
{
e.what();
}
}
执行结果:
solen@ubuntu:~/cpp$ ./try 4 B 1: myException
3 抛出类和子类的实例
同时捕捉时,如果首先捕捉父类的对象,那么子类的Catch将不会被捕获。
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();
}
直接声明throw的类型,但是这样以来,其他类型将不会被throw出去
