这是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.
时间: 2024-10-12 16:08:20