title: exception creating 2D Array: clean-up before re-throw in C++
body: <p>I want to have a function which dynamically creates and returns a 2D array or when memory allocation fails passes the exception <em>without</em> information loss <em>after</em> cleaning up already allocated rows:</p>
  
  <pre><code>double **create (int rows, int cols)
  {
      double **array = new double* [rows];
      for (int x=0; x&lt;rows; x++)
      {
          try { array[x] = new double [cols]; }
          catch (exception &amp;e)
          {
              x--;
              for (; x&gt;=0; x--)
                  delete[] array[x]; // clean up already allocated rows
              delete[] array;
              throw e; // pass exception
          }
          for (int y=0; y&lt;cols; y++)
              array[x][y] = 0; // initialize array
      }
      return array;
  }
  </code></pre>
  
  <p>So I can be sure, if create throws, there is no memory leak. But can I be sure, that the passed exception e is "the same" as if directy thrown by new and not catched?</p>
  
  <p>E.g.</p>
  
  <pre><code>int main ()
  {
      double **d;
      try { d = create (HUGE_x, HUGE_y); }
      catch (exception &amp;e)
      {
          // 1. e could be thrown by new double* [rows]
          //      e.g. if HUGE_x is already to huge
          // 2. e could be thrown by throw e
          //      e.g. if after some rows no memory anymore
          // in both cases: is e the same?
      }
      return 0;
  }
  </code></pre>
  
  <p>Or is it necessary to have <code>catch (bad_alloc &amp;e)</code> inside the <code>create</code> function? Or does it work only with <code>catch (...) { /* do clean-up*/ throw; }</code>? Is there the same problem as in C# with losing stack trace when re-throw is not with <code>throw;</code> simply?</p>
  
  <p>And another, more general question:</p>
  
  <pre><code>void f () { throw Object(); } // or throw "help";
  
  void main ()
  {
      try { f(); }
      catch (Object &amp;e) // or catch (char *)
      {
          // Where is the Object or C-String created on the stack in function f()
          // since we aren't any more in function f() but we are dealing with
          // references/pointers to a non-existent stack?
      }
  }
  </code></pre>