Friday, March 5, 2010

Right way to print details of .NET exception

The right answer is also the simplest way to achieve this – just use e.ToString(). This prints everything including the exception type, message, stack trace, walk the inner exceptions until the last one etc.

May sound too simple to warrant a blog – but I have seen numerous times people writing several lines of code and invariably missing some crucial piece of information.

Bad Ex#1:

catch(Exception ex)
{
    Log(string.Format("Encountered exception: {0}", ex.Message));
    Log(ex.StackTrace);
    return false;
}

This lacks exception type, inner exception details etc.

Bad Ex#2:

catch (Exception ex)
{
    Console.Error.WriteLine("Unknown/Unhandled exception got while running the process");
    Console.Error.WriteLine("Message: " + ex.Message);
    Console.Error.WriteLine("Stack  : ");
    Console.Error.WriteLine(ex.StackTrace);

    if (ex.InnerException != null)
    {
        Console.Error.WriteLine("Inner Exception: " + ex.InnerException.Message);
        Console.Error.WriteLine("Stack  : ");
        Console.Error.WriteLine(ex.InnerException.StackTrace);
    }

    exitcode = -1;
}

This is missing exception type, walking of inner exceptions beyond the first one etc.

So the lesson is quite simple – always use e.ToString() to print the complete information about an exception!