title: How does `try / catch` work in details
body: <p>I would like to the innards of how does <code>try {} catch {}</code> block and stack traces work.</p>
  
  <p>I was reading <a href="https://today.java.net/article/2006/04/04/exception-handling-antipatterns" rel="noreferrer">this great article about exception handling anti-patterns</a> and found the following paragraph:</p>
  
  <blockquote>
  <pre><code>catch (NoSuchMethodException e) {
    throw new MyServiceException("Blah: " +
        e.getMessage());
  }
  </code></pre>
    
    <p>This destroys the stack trace of the original exception, and is always wrong.</p>
  </blockquote>
  
  <p>After that I realized that I don't <em>really</em> know how <code>try/catch</code> works. My understanding is the following. Consider the example:</p>
  
  <pre><code>void top() {
      try {
          f();
      } catch (MyException ex) {
          handleIt(); 
      } finally {
          cleanup();
      }
  }
  
  void f() {
      g();
  }
  
  void g() {
      throw new MyException();
  }
  </code></pre>
  
  <p>When I call <code>top()</code>, the call chain  <code>top -&gt; f -&gt; g</code>
  leaves two <a href="http://en.wikipedia.org/wiki/Call_stack#Structure" rel="noreferrer">stack frames</a> on the call stack (for <code>top</code> and <code>f</code> functions). When the exception is raised in <code>g</code>,
  the program bubbles up the execution stack until it finds <code>try/catch</code> block that handles the exception. Meanwhile it frees the stack frames and attach stack trace information to some "magic" object that can be passed to <code>catch</code> and the stack trace can be printed.</p>
  
  <p>How does it know that the called function is "surrounded" with the try/catch block? Is this information bound to the stack frame? Like, a pointer to error handling block (some switch selecting a matching <code>catch</code> block), and a pointer to <code>finally</code> block? Why <code>e.getMessage()</code> is destructive in the example above (see the comments)?</p>
  
  <p>Note, I <em>know</em> how to use try/catch and exceptions, I want to know how does it work <em>inside</em>.</p>