Blog Post

throw exception - where is my call stack gone?

Monday, October 24, 2016 12:29 AM

Let me present common way of hiding exception source. I have put a small code together that illustrate the issue.

 

The example script has two parts class I am writing that has an exception and calling program. 

class Program
{
  static void Main(string[] args)
  {
    var js = new DemoClass();

    try
    {
        try
        {
            js.Richard();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }

    js = null;
    Console.ReadKey();
  }
}
public class DemoClass
{
  public void Richard()
  {
    throw new AccessViolationException("Exception");
  }
}

This exception will be thrown and we will be able to see that the exception does happen.

Where is the issue then? 

The issue shows up when application is written and we are getting exceptions either by code failing and exceptions bubbling up to user or into our exception handling framework, that logs call stack. We are ready to follow the code, or more likely someone from support team.

As developers we would be expecting exception originating at this line

throw new AccessViolationException("Exception");

Yet this is not true and the origin of the exception is at:

throw ex;

This is because the exception is caught and the same exception is being thrown at the point of throw ex;

We can fix the code by, removing ex

 

        try
        {
            js.Richard();
        }
        catch (Exception ex)
        {
            throw;
        }

 

This will now work same way and will keep the full stack all the way to the exception origin in Richard Method.