Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Add Temporary Verbose Error Messages to Your Catch Blocks

2.75/5 (4 votes)
14 Nov 2015CPOL 7.1K  
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)