When you write a catch clause, you must determine how the exception is passed into the catch clause. You can have three choices: as you pass arguments to a function, through a pointer (by pointer), through a value (by value) or by reference (by reference).
We first discuss catching an exception by means of a pointer (catch by pointer). Passing an exception to a catch clause from the throw is a slow process, and in theory the implementation of this method is the most efficient for the process. Because when exception information is passed, only methods that throw an exception through the pointer can be used to not copy the object, for example:
class exception { ... }; // 来自标准C++库(STL)
// 中的异常类层次
void someFunction()
{
static exception ex; // 异常对象
...
throw &ex; // 抛出一个指针,指向ex
...
}
void doSomething()
{
try {
someFunction(); // 抛出一个 exception*
}
catch (exception *ex) { // 捕获 exception*;
... // 没有对象被拷贝
}
}
It looks good, but that's not the case. In order for the program to work properly, the programmer must define the exception object to ensure that the object continues to survive when the program control leaves the function that throws the pointer. Both global and static objects can do this, but it is easy for programmers to forget this constraint. If that's the case, they'll write code like this:
void someFunction()
{
exception ex; // 局部异常对象;
// 当退出函数的生存空间时
// 这个对象将被释放。
...
throw &ex; // 抛出一个指针,指向
... // 已被释放的对象
}
This is simply awful, because the object that handles this exception's catch clause receives a pointer that no longer exists.