Visual Studio 2010!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
Retrieving Detailed Exception Information in C#
By Rick Leinecker

Rate This Article: Add This Article To:

Retrieving Detailed Exception Information in C# - ' StackTrace and TargetSite Properties'
( 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.



 
 
>>> More Microsoft Languages Articles          >>> More By Rick Leinecker