title: C#: Exception handling in recursive call
body: <p>I have a recursive method call. When any exception is thrown, I would like to see, where in the recursive call stack it happened. I have a field which holds a "path" which represents the recursion stack.</p>
  
  <p>Now I would like to add the path information to any exception that could possibly be thrown in the recursive call.</p>
  
  <pre><code>void Recursive(int x)
  {
    // maintain the recursion path information
    path.Push(x);
  
    try
    {
      // do some stuff and recursively call the method
      Recursive(x + 6);
    }
    catch(Exception ex)
    {
      if (ex is RecursionException)
      {
        // The exception is already wrapped
        throw;
      }
      // wrap the exception, this should be done only once.
      // save the path and original exception to the wrapper.
      throw new RecursionException(path.ToString(), ex);
    }
    finally
    {
      // maintain the recursion path information
      path.Pop()
    }
  }
  </code></pre>
  
  <p>It just looks too complicated. There is not only one method. There are probably twenty or even more places where I had to write this code.</p>
  
  <p>Is there any simpler way to implement this?</p>
  
  <hr>
  
  <p><strong>Edit</strong>: To point this out: I would like to have a much simpler situation where there is not such an overhead to recursively call the method, because I have many such recursive calls, there is not only one method, there are a couple of methods recursively calling each other, which is complex enough.</p>
  
  <p>So I would like to avoid the whole try - catch block, but I can't see any solution for this.</p>
  
  <p>It is not a big problem for Exceptions thrown in my own code, because it could include the path from the beginning. But it is a problem with every other exception.</p>
  
  <hr>
  
  <p><strong>Edit</strong>: The Exceptions need to be wrapped in any other code, not only when calling the recursive method:</p>
  
  <pre><code>  try
    {
      int a = 78 / x; // DivisionByZeroExeption        
  
      Recursive(x + 6);
  
      this.NullReference.Add(x); // NullReferenceException
    }
  </code></pre>
  
  <p>So wrapping only the call to Recusive does not work.</p>
  
  <p>there are many such methods, having different signatures, doing different things, the only common thing is the exception handling.</p>