异常处理

来源:互联网 发布:fatego斯卡哈技能数据 编辑:程序博客网 时间:2024/06/05 07:43
  • try/catch异常处理

程序如下:

#include <stdio.h>int main(){    //一个try可以尾随多个catch块    try    {        printf("try 块1代码执行\n");        throw 10;//产生一个异常    }    catch (int & i)//使用引用,省去复制开销    {        printf("处理try块1的int类型一场对象,值为%d\n", i);    }    catch (double &d)    {        printf("处理try块1的float类型一场对象,值为%f\n", d);    }    try    {        printf("try 块2代码执行\n");        throw 23.8;    }    catch (int & i)    {        printf("处理try块2的int类型一场对象,值为%d\n", i);    }    catch (double &d)    {        printf("处理try块2的float类型一场对象,值为%f\n", d);    }    printf("程序结束\n");    return 0;}

输出结果:

try 块1代码执行
处理try块1的int类型一场对象,值为10
try 块2代码执行
处理try块2的float类型一场对象,值为23.800000
程序结束

  • try/catch(…)异常处理
    如果要对try块代码产生的任意类型异常都进行处理,可以是要try(…):
//编译通过,运行出错        !!!!why?????#include <stdio.h>int main(void){    try    {        int a = 0;        int b = 32 / a;    }    catch(...)//产生异常    {        printf("error!!!\n");    }    return 0;}
  • 对抛出异常的函数调用代码进行try保护
#include <stdio.h>class A{public:    void f()    {        printf("函数f打印\n");    }    //void g() throw(int){ throw 12; }    void g()    {        throw 12;    }};int main(void){    A a;    a.f();    try    {        a.g();    }    catch (int & i)    {        printf("函数g出现异常,值为%d\n",i);    }    return 0;}

输出:
函数f打印
函数g出现异常,值为12

  • 异常类型列表
返回值类型 函数名(参数列表) throw (用逗号分隔可抛出的异常类型列表){    //函数代码}//上面g函数,可以写为:void g() throw(int){ throw 12; }

如果异常列表为空,则表示不会抛出任何类型的异常,如void f(int) throw ();没有throw说明的传统形式函数,如void f(),表示可以抛出任何类型的异常。

  • 继续抛出异常
#include <stdio.h>void f(void){    try    {        throw "abc";    }    catch (const char *)    {        printf("执行f出现const char *异常\n");        throw;//继续抛出所捕捉到的异常,然后函数返回     }    printf("f函数打印\n"); }int main(void){    try    {        f();    }    catch(const char *)//产生异常    {        printf("执行main出现const char *异常\n");    }    return 0;}

上述代码中,函数f捕捉到字符串异常后,继续把它抛出,由调用函数f的main函数进行最终的异常处理。
结果:
执行f出现const char *异常
执行main出现const char *异常

原创粉丝点击