|
本文讲关于C++的异常的所有东西:
绝对不让异常逃离析构函数
- 阻止exception逃离析构函数,主要是两个原因:
1 防止在异常处理过程中的栈展开行为时,将调用terminate函数。程序将会结束,有时候其实错误并没有那么严重。 [插入: 什么时候会调用terminate函数呢?] [回答 : By default, the terminate handler calls abort. But this behavior can be redefined by calling set_terminate. This function is automatically called when no catch handler can be found for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception handling process. //对于一个异常没有相应的catch语句块的话,就会自动调用terminate函数,或者是对于一些无法处理的异常的情况时。 This function is provided so that the terminate handler can be explicitly called by a program that needs to abnormally terminate, and works even if set_terminate has not been used to set a custom terminate handler (calling abort in this case). terminate被调用的情况: 1 当发送一个异常,并且构造函数产生异常 2 当发送一个异常,或者析构函数产生异常 3 一个静态对象的构造或者析构发送一个异常 4 以atexit注册的函数发生异常的时候 5 自定义一个异常,但是实际上没有异常产生的时候 6 调用缺省的unexcepted()函数时候 (unexcepted函数是因为该函数抛出了没有预期的异常) 2 可以协助确保destructor完成它应该完成的所有的动作。 #include
using namespace std; class myexception{}; class Session { public: Session() { logCreation(); } ~Session() { try{ //这里的try catch块是很重要的 logDestruction(); }catch(...){ cout << "catch exception..." << endl; } } private: static void logCreation(){cout << "enter..." << endl;} static void logDestruction() {cout << "out..." << endl;throw myexception();} }; int main() { Session s; return 0; }
catch的子语句块 VS.函数的调用 3大类的不同: 1 exception 对象总是被复制。如果以by value的方式,甚至复制两次。 2 , 被抛出作为exception的对象,允许的转换操作比“被传递到函数中”的少。 3 catch子句以其出现的顺序进行匹配,也就是 “first fit”的策略, 不像函数调用的 “best fit”的策略
|