Sunday, June 15, 2008

How to get all the (nested ) Inner Exceptions in the chain

Much of the time for a programer, it is more helpful to know about the inner exceptions occurred while performing a certain operation. In c# its much easy but less utilized technique for getting all the nested exceptions occurred. Getting all the exceptions is also more helpful in error logging and debugging. Below is the technique defined...

// the target code that might raise exceptions
catch (Exception ex)
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;

// output or save the full error message based on your case
//Response.Write (errorMessage); //or
// Console.WriteLine(errorMessage);