zoukankan      html  css  js  c++  java
  • Visual C++中的异常处理浅析(3)

    2.3异常处理函数

      在标准C++中,还定义了数个异常处理的相关函数和类型(包含在头文件<exception>中):

    namespace std
    {
     //EH类型
     class bad_exception;
     class exception;

     typedef void (*terminate_handler)();
     typedef void (*unexpected_handler)();

     // 函数
     terminate_handler set_terminate(terminate_handler) throw();
     unexpected_handler set_unexpected(unexpected_handler) throw();

     void terminate();
     void unexpected();

     bool uncaught_exception();
    }

      其中的terminate相关函数与未被捕获的异常有关,如果一种异常没有被指定catch模块,则将导致terminate()函数被调用,terminate()函数中会调用ahort()函数来终止程序。可以通过set_terminate(terminate_handler)函数为terminate()专门指定要调用的函数,例如:

    #include <cstdio>
    #include <exception>
    using namespace std;
    //定义Point结构体(类)
    typedef struct tagPoint
    {
     int x;
     int y;
    } Point;
    //扔出Point异常的函数
    static void f()
    {
     Point p;
     p.x = 0;
     p.y = 0;
     throw p;
    }
    //set_terminate将指定的函数
    void terminateFunc()
    {
     printf("set_terminate指定的函数\n");
    }

    int main()
    {
     set_terminate(terminateFunc);
     try
     {
      f(); //抛出Point异常
     }
     catch (int) //捕获int异常
     {
      printf("捕获到int异常");
     }
     //Point将不能被捕获到,引发terminateFunc函数被执行

     return 0;
    }

      这个程序将在控制台上输出 "set_terminate指定的函数" 字符串,因为Point类型的异常没有被捕获到。当然,它也会弹出图1所示对话框(因为调用了abort()函数)。

      上述给出的仅仅是一个set_terminate指定函数的例子。在实际工程中,往往使用set_terminate指定的函数进行一些清除性的工作,其后再调用exit(int)函数终止程序。这样,abort()函数就不会被调用了,也不会输出图1所示对话框。

      关于标准C++的异常处理,还包含一些比较复杂的技巧和内容,我们可以查阅《more effective C++》的条款9~条款15。

    上一页  [1] [2] [3] [4] [5] 下一页

  • 相关阅读:
    各种类型的Dialog
    短信验证码的使用
    监听开机广播
    实现点击两次返回键退出
    Android 遮罩层效果--制作圆形头像
    Native方法的使用
    如何给数字添加分隔符
    自定义Toast
    Android px、dp、sp之间相互转换
    android:scrollbarStyle属性及滚动条和分割线覆盖问题
  • 原文地址:https://www.cnblogs.com/adylee/p/1233066.html
Copyright © 2011-2022 走看看