Exception.ToString() and capturing inner exceptions

It is often worth going back to basics, it turns out quite a few people don’t realise that calling “.ToString” on an exception object in .NET, will provide a nicely formatted output suitable for logging. It will also recursively extract the inner exceptions, if there are any too.  It includes the stack trace. I’ve seen quite a few times now code that replicates the same functionality as this built in function. Here is the description from MSDN.

The default implementation of ToString obtains the name of the class that threw the
current exception, the message, the result of calling ToString on the inner exception,
and the result of calling Environment.StackTrace.
If any of these members is null, its value is not included in the returned string.

[MSDNException.ToString Method ()] 

This is quite helpful as it means no traversing the exception objects extracting the inner exceptions, if they exist as its already implemented in this method.

Add comment