Jim Fell
Jim Fell

Reputation: 14256

C# MessageBox Error Messages

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.

Upvotes: 9

Views: 26074

Answers (6)

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

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.

Upvotes: 0

Jamie Keeling
Jamie Keeling

Reputation: 9966

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.

Upvotes: 0

David Larrabee
David Larrabee

Reputation: 384

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.

Upvotes: 0

Matt Greer
Matt Greer

Reputation: 62027

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

Upvotes: 0

Jason Webb
Jason Webb

Reputation: 8020

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

Upvotes: 1

Rob Fonseca-Ensor
Rob Fonseca-Ensor

Reputation: 15621

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);

Upvotes: 9

Related Questions