这是一种在标准C++中实现类似Finally行为的好方法吗?(不使用特殊指针)
class Exception : public Exception
{ public: virtual bool isException() { return true; } };
class NoException : public Exception
{ public: bool isException() { return false; } };
Object *myObject = 0;
try
{
// OBJECT CREATION AND PROCESSING
try
{
myObject = new Object();
// Do something with myObject.
}
// EXCEPTION HANDLING
catch (Exception &e)
{
// When there is an excepion, handle or throw,
// else NoException will be thrown.
}
throw NoException();
}
// CLEAN UP
catch (Exception &e)
{
delete myObject;
if (e.isException()) throw e;
}
- 对象未抛出异常 -> 无异常 -> 对象被清理
- 对象抛出异常并被处理 -> 无异常 -> 对象被清理
- 对象抛出异常并未被处理 -> 抛出异常 -> 对象被清理 -> 异常继续传递