Rethrowing More Expressive Exceptions in C#

This post was contributed by Jonathan Hamm, one of the developer gurus I have the privilege of working with at my day job.

I did not realize this behavior with rethrowing exceptions existed where information can be added to the exception by the “catch” then in subsequent “catch” blocks the data will remain. It does make sense now with this test.

The inner most method throws an error, the next level adds an element to the Data property then rethrown, then the main level catches the exception that has the additional Data property.

LINQPad>

void Main()
{
      try
      {            
            LogAndRethrow();
      }
      catch (Exception ex)
      {
            ex.Data.Dump();
      }
}

void LogAndRethrow()
{
      try
      {
            CreateException();
      }
      catch (Exception ex)
      {
            ex.Data.Add("caught and rethrown", true);
            throw;
      }
}

void CreateException()
{
      throw new NotImplementedException();
}

Jon used LINQPad to explore this feature and run the code above. Actually, he does a lot of amazing things with LINQPad you should definitely give this tool a try if you haven’t already. Speaking of LINQPad, did you know you can run LINQPad scripts from the command line with lprun? Something to think about if you are looking to use your C# skills for continuous delivery automation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s