c++ - exception catch all handler

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.



we will come back to the initialization resource aquisition later .

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值