String Writer

my tech stuffs…

Iterate all Inner Exceptions in C#

with 3 comments

In simple applications or pages, handling an exception will not be a difficult task. But when your application is using any web services or threading, most of the time, actual exception details will be stored in InnerException of the main Exception object. In such cases, we need to iterate all the inner exceptions to get the actual error message.

Here is a code snippet to iterate all inner exceptions from the root Exception object.


private List<string> GetAllErrMessages(Exception ex)
{
   List<string> messages = new List<string>();
   //assign the current exception as first object and then loop through its
   //inner exceptions till they are null
   for(Exception eCurrent = ex.Exception; eCurrent != null; eCurrent = eCurrent.InnerException)
   {
      messages.Add(eCurrent.Message);
   }
}

My team said they never saw any code like handling Exception objects using for loop. I don’t know but I learnt this from my lead when I was working on Adrenalin HRMS product. Just sharing the code for your review ;)

About these ads

Written by visvabalaji

July 26, 2011 at 4:43 pm

Posted in C#

Tagged with , ,

3 Responses

Subscribe to comments with RSS.

  1. [...] the helper method, a ‘GetAllErrorMessages’ method is being used to iterate through all the inner [...]

  2. I believe you can get rid of the loop altogether by simply calling ex.ToString(); Calling ToString() on an exception object provides the message and also the stack trace for both the main exception and inner exceptions.

    Fred G. Vader

    April 18, 2012 at 4:09 pm

  3. Great idea! Helped me out. Thanks for sharing :)

    stevehansengeotab

    December 31, 2012 at 12:33 pm


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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: