I was just reading an article on Builder.com about exception handling and it reminded me of some of my pet peeves regarding exception handling.

  1. Don't assume you have permissions to write to the Event Log! - Many people add code to log exceptions to the Event Log however they do not add any exception handling in case it fails. This is especially true for ASP.NET as many corporate networks are severely restricting permissions. It is possible for the System.Diagnostics.EventLog.WriteEntry() to throw exceptions! The exception for permissions issue is System.Security.SecurityException.
    • Best practice is to use a wrapper function write the information. This also makes it possible to abstract which event log to write to instead of hard-coding to System.Diagnostics.EventLog. For more information search the net for classes such as LogException or use the Microsoft Patterns & Practices Exception Handling Block.
    • Use regedit to give permissions to write to the Event Log. Open regedit to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security and right-click on the node and select Permissions. For ASP.NET add the ASPNET user if you are using Win2k3 or 'NETWORK SERVICE' for WinXP. See this blog entry for more information.
  2. Don't throw away the handled exception! - If you "re-throw" the exception or derive another exception type, do not discard the current exception information. It makes debugging applications so much more difficult without that information. Do not display the gory details to the end user, but at least provide a means to debug the application.
// Example poor exception handling from a DAL.
// Not my code, but just an example. Comments reflect code deficiencies.
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = SqlConn;
    cmd.CommandText = "...";
    cmd.CommandType = CommandType.StoredProcedure;
catch (Exception ee)
    // Notice only the ee.Message is used
    // so extended details (StackTrace, etc.) are lost
    // the catch should have specified DBException first
    throw new DBException(ee.Message); // BAD! BAD! BAD!

Updated: 2007-05-04 09:05:48 -05:00 Added comments to bad exception handling example.

Comment Section

Comments are closed.