zoukankan      html  css  js  c++  java
  • How exception works ?

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

    February 18, 2013

    How exception works ?

    Filed under: c++ — Tags: , , — 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.
  • 相关阅读:
    Socket异步通信
    以读取博客园随笔备份为例 将xml 序列化成json,再序列化成对象
    NhibernateProfiler写个自动破解工具
    关于下载GAE High Replication Datastore数据
    .text 0.958 数据添加
    C#实现RTP数据包传输参照RFC3550
    在线商城表结构
    相似字符串
    .net 4.0 的Socket写的支持跨平台双工的轻量级通讯组件
    写一个迷你版Smarty模板引擎,对认识模板引擎原理非常好(附代码)
  • 原文地址:https://www.cnblogs.com/raison/p/5573128.html
Copyright © 2011-2022 走看看