异常处理

来源:互联网 发布:淘宝上传视频怎么传 编辑:程序博客网 时间:2024/06/06 23:17

在刚看到这个概念的时候,我第一反应就是,用if不就行了,干嘛这么麻烦。后来我才知道,如果特殊情况比较多,if语句要不断的写重复性的代码,而异常处理可以一次处理一类的情况,所以学习异常处理是很必要的。



第一部分:介绍了throw try  catch

#include<iostream>using namespace std;int main(){    try//是用来执行的程序    {        throw 'a';                      //再换成throw 100;试一试。<span style="white-space:pre">try相当于return    }    catch(int)<span style="white-space:pre"></span>//相当于if,括号里是接受throw的类型。    {        cout<<"int"<<endl;    }    catch(char)    {        cout<<"char"<<endl;    }}





第二部分:实例。

#include <iostream>using namespace std;int show(float a,float b){    if(b==0)        throw 'n';    else        return 666;}int main(){    try        {            cout<<show(1,0);        }    catch(int)    {        cerr<<666<<endl;    }    catch(char)    {        cerr<<"b can't be 0"<<endl;    }}

感觉不错,请点个赞。哪错了,请指出。


1 0
原创粉丝点击