C# Debug Exception Viewer

January 24, 2023

It’s simple enough to add a try/catch block around code to catch any exception. But when you are in the initial stages of generating code, you want quick feedback and it doesn’t exactly need to be pretty. In the catch block, pass the exception to this method to create a string with easy to read information.

The Code

Here is an example of where you would call this exception viewer method.

try
{
    // bad code!
}
catch (Exception ex)
{
    DisplayExceptions(ex);
    throw;
}

Below is the exception viewer method. After creating a string the encapsulates the failed status, I display it in a message box. Obviously you would not do this in production code. Instead you could log it as appropriate.

static void DisplayExceptions(Exception exception)
{
	Exception ex = exception;
	string errMsg = "";
	int index = 1;
	while (ex != null)
	{
		if (errMsg.Length > 0)
		{
			errMsg += "\n\n";
		}

		errMsg += $"{index}: {ex.GetType().Name}\nMessage: {ex.Message}";

		if (ex is System.Reflection.ReflectionTypeLoadException)
		{
			var typeLoadException = ex as ReflectionTypeLoadException;
			var loaderExceptions = typeLoadException.LoaderExceptions;

			foreach (var loaderEx in loaderExceptions)
			{
				errMsg += $"\n    ---- {loaderEx.Message}";
			}
		}

		// Move to next lower exception.
		ex = ex.InnerException;
		index++;
	}

	MessageBox.Show(errMsg, "Exception Viewer", MessageBoxButtons.OK);
}

Some example exception displays might be:

File Not Found Exception
Load Exception buried under several other exceptions