views:

373

answers:

6

Hello. In my application I am using message boxes to display error information.

try
{
   // Something...
}
catch (SystemException ex)
{
   MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

This was fine at first, but as my program grows it becomes increasingly difficult to find the try-catch block where this error is generated. Is there a way to display the line of code or function in which the error was generated? I am using Microsoft Visual C# 2008 Express Edition. Thanks.

+3  A: 

This will give you a LOT of information about the method that caused the error (the stacktrace)

MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Rob Fonseca-Ensor
+1  A: 

Just display the Exception.StackTrace. It will contain all kinds of helpful info that should help you find the offending line of code.

Jason Webb
A: 

There is Exception.StackTrace, which is often a bit much for a message box. Also Exception.TargetSite.Name should be helpful too.

Matt Greer
A: 

you want to review the ex.StackTrace() which will give you full details of the location of the thrown exception. You might want to also check the InnerException.

David Larrabee
A: 

Why don't you add some extra information to the error message to allow you to find it more easily? You could add some more text after the "Error" string depending on where abouts the message box is being created.

The exception that is thrown contains several functions to allow you to get a more detailed explanation of an error.

Jamie Keeling
I don't want to think up a new error message (that I will likely never see) for every possible catch block.
Jim Fell
I mean along the lines of using the ex.ToString(), not manually adding text.
Jamie Keeling
A: 

There are a few options that you have available to you.

  1. Put something in your message box if you want to give context information
  2. Show the stack trace information, if on a debug build line numbers will be included

However, I would caution around this practice, if you are finding that you are getting too many and you can't figure out where, I would start to look at re-structuring your code to ensure that you don't have issues.

Mitchel Sellers
I don't want to think up a new error message (that I will likely never see) for every possible catch block.
Jim Fell