2007-06-07
| Table of Contents: |
| Rate This Article: | Add This Article To: |
( Page 2 of 2 )
The StackTrace Property
You can examine the stack trace programmatically by using the Exception object's StackTrace property. You can display it when you're debugging a program to trace the chain of execution in the code through which the exception has passed. I don't recommend displaying it in production applications since users may get very confused. But you can take a look at it from your program code, and in some situations gain greater insight into how to deal with the error.
The following code shows how to display the stack trace for our DoFileIO method:
void DoFileIO()
{
try
{
Open(@"c:\MissingFile.dat");
Read();
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
The TargetSite Property
I'd like to mention another useful piece of information that you can get from the Exception class. The name of the method that throws the exception is contained in the Exception class's TargetSite property. To retrieve the method name, you must use the Name member of the TargetSite property. The following code displays the method name in a message box:
try
{
DoFileIO();
}
catch (Exception ex)
{
MessageBox.Show(ex.TargetSite.Name);
}
Conclusion
Now that you have a way to get additional information from exceptions, you may have an easier time debugging your applications. And since that can sometimes be a very difficult and tedious process, you might save a lot of time.
![]() |
|


