c++ - exception catch all handler _C/C++_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > C/C++ > c++ - exception catch all handler

c++ - exception catch all handler

 2012/9/8 11:51:02  joe.bq.wang  程序员俱乐部  我要评论(0)
  • 摘要:thisisacodethatshowshowyoudothecatchallexceptionhandlerinC++;itmaysoundplatitude,butC++lacksofthetypesystemwhichdictatethatalltheexcpetionshouldderivefromtheExceptionbaseclasssotocatchallexception,nomatterwhichtypeitis(mayitbeanprimitivetype,astring
  • 标签:Handler c++ all

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 .

?

?

上一篇: CRC16位校验 下一篇: c++ function try block
发表评论
用户名: 匿名