c++ throw try catch

来源:互联网 发布:淘宝宝贝怎么修改类目 编辑:程序博客网 时间:2024/06/05 01:12
#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++定义的一个异常类

0 0
原创粉丝点击