您的位置:首页 > 编程语言 > C语言/C++

c++ try throw简单例子

2015-07-14 17:08 302 查看
#include<iostream>

using namespace std;

int main()

{

        int a,b;

        char tmp[]="haha";

        double total=1.0;

        cin>>a>>b;

        if(b>0){

                for(int i=0;i<b;i++){

                        total*=a;

                }

        }else if(b<0){

                try

                {

                        if(a==0){

                                throw tmp;

                        }

                        for(int i=0;i<-b;i++){

                                total*=a;

                        }

                        total=1/total;

                }

                catch(char*){

                        cerr<<"error\n";

                        return 1;

                }

        }else{

                        if(a==0){

                                throw a;

                        }else{

                                total=1;
                        }

        }

        cout<<total<<endl;

        return 0;

}

在可能出错的代码前后加上try语句,在可能错误语句里用throw丢出一个变量(无限制),然后用catch捕捉这个变量类型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: