You can notice many changes in this blog. Hope you like this new look and feel. If you have some ideas or complaints, leave the message below. We'll fix that. :)
My story today is about exception stack trace. How we gonna make use of inner exception. For example, I call obj1, then obj1 calls obj2. If error occurs in obj2, obj2 throws its error which has the type Obj2Exception. This error also defects obj1, so obj1'll throw Obj1Exception as well. In conclusion, obj2 throws Obj2Exception and obj1 throws Obj1Exception respectively.
We need to know the stack trace of calling those exceptions but how? How about using Exception.StackTrace in the catch(..) block? In that case, you'll get the result like:
at ExceptionTest.Program.MockObject.DoOuterTask() in C:\Documents and Setting
s\winladen\My Documents\Visual Studio 2008\Projects\ConsoleApplication1\Exceptio
nTest\Program.cs:line 35
at ExceptionTest.Program.Main(String[] args) in C:\Documents and Settings\win
laden\My Documents\Visual Studio 2008\Projects\ConsoleApplication1\ExceptionTest
\Program.cs:line 44
Which I don't need. Instead, using innerException 'd be more concise. I'll show you this example. Suppose I have this class:
class MockObject
{
public void DoInnerTask()
{
throw new MyInnerException("error: DoInnerTask()");
}
public void DoTask()
{
try
{
DoInnerTask();
}
catch (Exception e)
{
throw new MyException("error: DoTask()", e);
}
}
public void DoOuterTask()
{
try
{
DoTask();
}
catch (Exception e)
{
throw new MyOuterException("error: DoOuterTask()", e);
}
}
}
The method's called like in a stack fashion, as you see.
public class MyInnerException : Exception
{
public MyInnerException(string message) : base(message) { }
public MyInnerException(string message, Exception innerEx) : base(message, innerEx) { }
}
public class MyException:Exception{
public MyException(string message) : base(message) { }
public MyException(string message, Exception innerEx) : base(message, innerEx) { }
}
public class MyOuterException : Exception
{
public MyOuterException(string message) : base(message) { }
public MyOuterException(string message, Exception innerEx) : base(message, innerEx) { }
}
Ok, the point in this story's here, we make use of iteration of innerException in the catch(..) block:
static void Main(string[] args)
{
try
{
MockObject obj1 = new MockObject();
obj1.DoOuterTask();
}
catch (Exception e)
{
for (Exception e1 = e; e1 != null; e1 = e1.InnerException)
{
Console.WriteLine("Error type: "+e1.GetType());
}
}
}
The result:
Error type: ExceptionTest.MyOuterException
Error type: ExceptionTest.MyException
Error type: ExceptionTest.MyInnerException
We print the types of exceptions thrown; fill in the detail you need for the stack trace by yourself.
Hope this help!

63a95149-2fd6-43ff-a902-580d45551e0b|0|.0