Tuesday, June 10, 2008

Use Exception.ToString() instead of Exception.Message

All too often I see code that tries to log exceptions to some type of persistent storage for and later reference and error/bug tracking. Some might not be aware, but the second worst thing you can log is Exception.Message. (The first being "An error occurred.") What should you use instead? Exception.ToString()

There is a world of difference between the two. Here's an example:

   1: public partial class Default : System.Web.UI.Page
   2: {
   3:     protected void Page_Load(object sender, EventArgs e)
   4:     {
   5:         try
   6:         {
   7:             int zero = 0;
   8:             int divisionbyZero = 42 / zero;
   9:         }
  10:         catch (Exception caughtException)
  11:         {
  12:             System.Console.WriteLine(caughtException.Message);
  13:             System.Console.WriteLine(caughtException.ToString());
  14:         }
  15:     }
  16: }

When I debug, here is what I get from line 12:

Attempted to divide by zero.

And from line 13:

System.DivideByZeroException: Attempted to divide by zero.
   at Demo.Web.Default.Page_Load(Object sender, EventArgs e) in C:\Working Copies\Demo\Demo.Web\Default.aspx.cs:line 23

Which would you rather see in a system error log?

My recommendation when writing to an error log "Use Exception.ToString() instead of Exception.Message."