#include <iostream>
using namespace std;
double fuc(double x, double y) //定义函数
{
if(y==0)
{
//throw y; //除数为0,抛出异常
throw exception();
}
return x/y; //否则返回两个数的商
}
void main()
{
double res;
try //定义异常
{
res=fuc(2,3);
cout<<"The result of x/y is : "<<res<<endl;
res=fuc(4,0); //出现异常
}
//catch(double ) //捕获并处理异常
//{
// cout<<"error of dividing zero.\n";
// //exit(1); //异常退出程序
//}
catch(exception& ) //捕获并处理异常
{
cout<<"error of dividing zero.\n";
//exit(1); //异常退出程序
}
cout<<"finished";
}
发生异常时候,(除数为0),需要抛出异常,即throw,进而执行catch语句;
正常时候,执行完try后,直接跳过catch,这里会涉及到栈解退(unwinding the stack),示意图:
(<<c++ primer plus 6th edition>>:中文版 page.625)
需要注意的是,catch语句类似函数定义,但即使用了引用,也产生临时拷贝
即 catch(exception& ) 与catch(exception )是一回事,编译器都产生一个临时拷贝
其中exception是c++定义的一个异常类