<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Exception on 菜菜博士</title>
    <link>https://microcai.org/tags/exception.html</link>
    <description>Recent content in Exception on 菜菜博士</description>
    <generator>Hugo</generator>
    <language>zh-cn</language>
    <lastBuildDate>Sun, 09 Apr 2017 00:00:00 +0800</lastBuildDate>
    <atom:link href="https://microcai.org/tags/exception/feed.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>使用异常实现cache</title>
      <link>https://microcai.org/2017/04/09/simple-cache-container.html</link>
      <pubDate>Sun, 09 Apr 2017 00:00:00 +0800</pubDate>
      <guid>https://microcai.org/2017/04/09/simple-cache-container.html</guid>
      <description>&lt;p&gt;异常用来做错误处理的时候，程序到处都是 try  cache ，代码十分的丑陋，我是不怎么喜欢的，我喜欢 asio 那种用 error_code  汇报错误 —— 不传 ec 的时候就抛异常，传就不抛，改为写入错误到 ec。&lt;/p&gt;
&lt;p&gt;但是，异常用来做流程控制，又特别的好用。流程控制，无非顺序、选择、分支和循环。在 c++里，又比 C 多了一个异常。在嵌套很深的地方，跳出逻辑，除了异常，就没有其他更好的办法了。&lt;/p&gt;
&lt;p&gt;在编写软件的时候，时常需要对一些数据做 cache。在使用的时候，要先检查 cache，存在则使用 cache ，不存在则按照老办法办，然后存入 cache。&lt;/p&gt;
&lt;p&gt;每次使用前都进行判断， 污染了快速路径的代码，对有简洁洁癖的程序员来说，内心是十分的纠结的。&lt;/p&gt;
&lt;p&gt;这个时候， 你就需要 异常。将 cache hit 作为正常的流程进行编写， 假定全部的数据都是在 cache 里的。这万一发生了 cache miss ， 则抛出异常，并在异常处理重新载入数据。然后重启处理。&lt;/p&gt;
&lt;p&gt;说到重启处理， 在 Windows 的 SEH 里，存在 &lt;code&gt;EXECEPT_CONTINUE_EXECUTION&lt;/code&gt; 这个异常处理的结果， windows 看到异常处理函数返回这个，就会回到发生异常的地方重新执行。然而这毕竟是一个 Windows 系统特有的 SEH ， 而且依赖底层CPU提供的机制。 编写C++是断然不能使用这套机制的。&lt;/p&gt;
&lt;p&gt;思考的最终结果，就是下面这样的结构&lt;/p&gt;
&lt;pre tabindex=&#34;0&#34;&gt;&lt;code&gt;
for (int =0; i &amp;lt; retry_times ; i++)
{ 
    try  
    {
            auto  v = cache_map_sometype.get_cache(key);
            // process with v ....
            ........
    }  
    catch(cache_miss&amp;amp;)
    {   
           // load v from other resources, database, filesystem, network, etc.
           ......
            cache_map_sometype.add_cache(key, v);
            contine; // NOTE about this.
    }
    break;  
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;在正常处理流程里， 执行到最后会有个 break 退出 for 循环。所以 for 循环在 cache hit 的状态下只执行一次。在 cache miss 的时候， catch block 里最后有一行 continue 。 于是就重启处理过程了。&lt;/p&gt;</description>
    </item>
  </channel>
</rss>
