Friday, June 13, 2008

Stacking Exceptions

The System.Exception object has an interesting member "InnerException".

Which solves the age old delimma "I caught an exception, now what do I do with it?"

By adding context to where the exception was caught you can assist the troubleshooting that will occur in production. This is because the "ToString" method will faithfully walk down the list of all the exceptions and report their contents as the following code shows.

====Code Starts=======

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplicationNestedException
{
class Program
{
static void Main(string[] args)
{
Exception exception = OuterException();
Console.WriteLine(exception.ToString());
Console.ReadLine();
}

static public Exception OuterException()
{
Exception twoDeep = new Exception("Two Levels Deep");
Exception innerException = new Exception("Inner Exception",twoDeep);
return new Exception("Outer Exception",innerException);
}
}
}

===End Code, Output Follows====

System.Exception: Outer Exception --->
System.Exception: Inner Exception --->
System.Exception: Two Levels Deep
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---

No comments: