Click here to Skip to main content
15,902,299 members
Articles / Programming Languages / C#
Tip/Trick

Add Temporary Verbose Error Messages to Your Catch Blocks

Rate me:
Please Sign up or sign in to vote.
2.75/5 (4 votes)
14 Nov 2015CPOL 7K   3   1
How to use temporary MessageBox.Show()s in your C# app to quickly see data about exceptions

Catch Me If You Can

You don't want your users to be bothered by message boxes showing up with cryptic information, so this is not code you would want to leave in before deployment to "normal people," but as a quick way to get detailed information on exceptions that are thrown while you are in the testing / development phase, showing yourself the exception Message, Source, and StackTrace all in one dialog can be a useful technique. To do so, just add code like this to any potentially exception-throwing methods:

C#
catch (Exception ex)
{
    String exDetail = String.Format(ExceptionFormatString, ex.Message, Environment.NewLine, ex.Source, ex.StackTrace);
    MessageBox.Show(exDetail);
}

The information you get will often be more specific, especially as regards line numbers of where problems are occurring, than you would otherwise see.

You may have noted that the String.Format() uses a constant, namely "ExceptionFormatString". This is a good practice, so that if you want to change it, after adding the above code to 40-eleven methods, you can just change it one place. Anyway, here it is:

C#
public static readonly String ExceptionFormatString = "Exception message: {0}{1}Exception Source: {2}{1}Exception StackTrace: {3}{1}";

Happy Debugging!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
QuestionThis is a antipattern! Pin
sx200821-Nov-15 7:48
sx200821-Nov-15 7:48 
Don't put MessageBox.Show() in Catch-Blocks; this is a Antipattern i've seen so many times. Unsure | :~
Imagine your code is called from inside a loop.
Do you want to confirm a Messagebox with a error message hundreds or thousand times?
The only thing you can do in this situation is to kill the application with the task manager.

Don't even try to apply this antipattern temporarily!

This is the right way to handle exceptions:
1.) install a event handler at the top-level
C#
static class Program
{
    // The main entry point for the application.
    static void Main()
    {
        Application.ThreadException += ApplicationThreadException;
        Application.Run(new Form1());
    }

    private static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
    {
        Exception ex = e.Exception;
        MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        // optionally log the exception
        MyLoggingFramework.LogException(ex);
    }
}
2.) create a special ExceptionDialogForm to present the exception in a nice way to the user:
C#
private static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
{
    Exception ex = e.Exception;
    var myform = new ExceptionDialogform(ex);
    myform.ShowModal();
}

Exceptions can contain Inner Exceptions.
All inner exceptions should displayed to the user as well.

3.) catch and re-throw exceptions
C#
public void LoadGameLevel(int level, string filename)
{
   try
   {
       // many lines of code here
       ....
   }
   catch(Exception ex)
   {
      // throw an new exception that explains whats was going wrong
      // and append the current exception as inner exception
      throw new GameException(String.Format("can't load game level {0} from file <{1}>",level, filename), ex);
   }
}

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.