this is a code that shows how you do the catch all exception handler in C++; it may sound platitude, but C++ lacks of the type system which dictate that all the excpetion should derive from the Exception base class so to catch all exception , no matter which type it is (may it be an primitive type, a string, or an exception derived class or even a custom class) you can catch and handle it also, there is no such finally keyword that can do some resource release work, so it is adviced that you can use the catch all and do the proper deallocation there.
below is the fake/mock code that show an typical resource class.
class resource
{
public:
void lock() ;
void releaes();
};
void resource::lock() { }
void resource::releaes() { }
and follow is the code that uses the catch all exception handlers as follow.
void catchCallHandler()
{
resource res;
res.lock();
try
{
// use res
// some action that causes an exception to be thrown
res.releaes();
}
catch (...) // ... the tree dots are refered as the ellipsis, which is quite often used in many a place.
{
res.releaes();
throw; // and you can rethrow the exception after you do the proper deallocation of the resources
// or you can opt not rethrow, but you can just return if the handler have handled the exception safely
}
res.releaes();
}
however, though we have the way to use the catch all handlers, we have a better way in C++;
though we discussed the catch (...) expression , it is not the only way of recover from the exception site, a better way and a more native way is to use the C++'s resource initialization is the resource aquisition paradigm/paragon. whereas the destructor which exit the function Will take responsibility of cleaning up the resource.
本文介绍了C++中如何实现捕获所有类型的异常,并通过示例代码展示了资源类的锁与释放操作。同时,文章对比了使用catch(...)与资源获取初始化(RAII)两种方式处理异常的区别。
5032

被折叠的 条评论
为什么被折叠?



