7.5. Getting Exception Information
Problem
There are several different methods of getting exception information. You need to choose the best one to use.
Solution
The .NET platform supports several mechanisms for displaying exception information, depending on the specific type of information that you want to show. The easiest method is to use the ToString method of the thrown exception object, usually in the catch block of an exception handler:
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}Another mechanism is to manually display the individual properties of the exception and iterate through each inner exception, if any exist. The default Exception.ToString method will iterate over the inner exceptions as well, so if you want to make sure you get all of that information, you need to roll over them when examining the properties directly. For example, the extension method shown in Example 7-3 is called from a catch block. ToFullDisplayString is called directly from the exception object and proceeds to display its information, including information on all inner exceptions and the exception data block.
Example 7-3. Displaying exception information, including information on all inner exceptions and the exception data block
public static string ToFullDisplayString(this Exception ex) { StringBuilder displayText = new StringBuilder( ); WriteExceptionDetail(displayText, ex); foreach (Exception inner in ex.GetNestedExceptionList( )) // from 7.14 { displayText.AppendFormat("**** INNEREXCEPTION ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access