How exception works ?

这是2013年写的一篇旧文,放在gegahost.net上面 http://raison.gegahost.net/?p=28

February 18, 2013

How exception works ?

Filed under: c++ — Tags: C++ constructor., C++ exception handling, C++ internal — Raison @ 10:23 am

(original works by Peixu Zhu)

1. Throw Exception

  • Set the size of the exception and then call internal routine __cxa_allocate_exception to allocate memory.
  •  __cxa_allocate_exception call malloc to allocate memory.  plus 0x78 bytes buffer to install default handlers later. if allocation fails, globally lock and throw an emergency exception, then globally unlock. If allocation successes, the  __cxa_allocate_exception routine return the address of the memory block minus 0x78 bytes.
  • Set the exception data as first argument,   and typeinfo as second argument,  then call internal routine __cxa_throw .
  • In __cxa_throw,  the routine installs default handlers in sequence at the additional memory provided in the first argument. and then unwind the stack  to match and call catch block by calling  __Unwind_RaiseException (in libunwind).

2. Catch block

  • Call dyld_stub___cxa_begin_catch.
  • Perform the blocked code.
  • Call dyld___sub_cxa_end_catch, the allocated exception object will be released.

3. Notes

  • As above, the code in catch{…} block should be strictly scoped in the block, and the exception object should be as simple as possible, any unexpected errors in the exception object will cause unexpected problems, and difficult to locate or debug it.
  • In addition to catching the exceptions thrown in codes, we should also catch default exceptions like std::bad_alloc, since the internal routine may throw such exceptions potentially.
  • It is not suggested to throw exceptions in any constructor methods, for causing unexpected results. If we throw an exception in a constructor method, we’ve in fact get a memory block for the object, though the memory address is not returned to calling routine, thus, the exception handler can not get the address information at all, and can not free the allocated memory explicitly or implicitly. Since the object is not created successfully, the destructor will not be called automatically.

转载于:https://www.cnblogs.com/raison/p/5573128.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值