在标准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。