程序员会试图预防意外情况发生,C++异常就为处理这种情况提供了一种功能强大而灵活的工具。
异常处理分为三部分:
1、引发抛出异常
2、捕获异常
3、使用try块
•Intermixing program and error-handling logic–Consider pseudocodePerform a task
If the preceding task did not execute correctly
Perform error processingPerform next task
If the preceding task did not execute correctly
Perform error processing–Can make program difficult to read, modify and debug
把业务代码和错误处理混合在一起,其实是一种不好的代码逻辑,维护性、可读性和性能都会下降
•An exception is an object of some class representing an exceptional occurrence.•Exceptions fall naturally into families.•Organizing exceptions into hierarchies ( derived exception classes ) can be important for robustness of code.
好处:只用一个catch就可以捕捉派生类
两种实现差别:第一种用基类的对象去捕获派生类的对象,就可能会发生数据成员切片现象。
如果我们抛出的对象的数据类型和catch的类型不一样时是不可以的,只有下面这种情况可行
[1] if H is the same type as E.
[2] if H is an unambiguous public base of E.
[3] if H and E are pointer types and [1] or [2] holds for the types to which they refer.
[4] if H is a reference and [1] or [2] holds for the type to which H refers.
引发异常时将复制该异常。( 初始化 ) 因此,它有义务定义异常类的复制构造函数,即实际参数对形式参数进行初始化。
The handlers are tried in order they were placed
Resources Management
•When a function acquires a resource ( such as open file, allocate memory, set an access control lock etc. ) , it is essential for the future running of the system that the resource be properly released.
void use_file(const char* fn)
{
FILE* f = fopen(fn,"r");
… // use f
fclose(f);
}
/* what about exception occurs when using f, result in not running fclose() ? */
RAII技术:调用析构函数时,将独立于函数是正常退出还是由于引发异常而退出。 异常处理机制使我们能够从主算法中删除错误处理代码。 堆栈展开 – “向上搜索堆栈”以查找异常的处理程序的过程。当调用堆栈被解除时,将调用构造的本地对象的析构函数。
2,3,4,5被destroy了