Questions about .net Exceptions

One of my readers emailed me the following question

I have a simple questions that my management asks me. When I see all kinds of exceptions thrown (null exceptions etc..), what is the user experience? Does their system hand these back to the user? does it return an error message? or simply crashes?

How can I determine the user experience pertaing to these exceptions?

My answer

The answer depends very much on the type of exception that is thrown, where it is thrown from and of course if it is caught or not.

In the eventviewer (if running .net 2.0) you will see all exceptions that are thrown. 

Case #1

Most applications throw a number of NullReference exceptions because they have code similar to this one

try{
  UserName = Request.Cookies["UserName"].Value;   
}
Catch(Exception ex){
  // handle the exception
}

In this case, if Request.Cookies["UserName"] does not exist, you will of course throw a NullReferenceException when trying to do .Value, but the code handles it, so if this is the case then the answer is, no, the user will not see an error page or get an exception but depending on the logic on your site it might cause issues in other places.   The preferred way here would be to check if  Request.Cookies["UserName"] is null before doing .Value on it to avoid the nullref and handle the situation correctly. 

Basic rule of thumb, if a value may or may not be null, check if it is null before using it to avoid throwing an exception.

Case #2

If the code above was in an aspx page and you do not have try/catch around it then it would display an error message to the user.  It might be the exception/stack page if you havent turned <customErrors> in web.config, or a custom errors page if you have that set up.

In this case you will see an HttpUnhandledException in the eventlog.

Case #3

If the code above (or any code resulting in an exception) is running in a winforms, windows service app or on a non-request thread (timer thread, finalizer etc.) in ASP.NET it will crash the process unless you have turned on legacy exception handling.  If you are on 1.1. or use legacy exception handling in 2.0 it will not crash the ASP.NET service, instead it will stop processing at the sight of the exception leaving potential room for memory leaks etc. to occurr (if the excception occurred before cleaning up all native resources).  

Laters,
Tess