Tuesday, September 30, 2008

Unhandled Exception Processing In The CLR

In this article published in MSDN September, the author categorized 3 situations where an exception would occur in the CLR and what would happen if not catched in the CLR.

  1. Exceptions in managed code
  2. Exceptions in unmanaged c++ coded which is invoked via P/Invoke in managed code
  3. Exceptions in managed code which is called via CLR Hosting API or COM Interop in native code

For situation 1 and 2, when a managed exception is not catched, the exception is swallowed by the CLR, if it happens in a thread created using System.Threading.Thread class, in the Finalizer thread or in the CLR thread pool threads. Otherwise, UnhandledException event is raised as part of the CLR's unhandled exception processing, which terminates the process. We can register an event handler to log about the failure for later diagnosis.

For situation 3, if an exception is thrown in a thread created in the CLR, in the .NET Framework 1.0 and 1.1, the CLR swallows the exception, while in the .NET Framework 2.0 and later, the CLR lets it go unhandled after triggering its unhandled exception process. On the other hand, if that exception is thrown on the thread created outside the CLR, the exception is wrapped as SEH Exception, and propagated backed to the native code.

Managed exceptions, if rethrown or packaged as inner exceptions as the following, the CLR would reset the starting point of the exception. The implication is that you may observe the point of failure is changed to that line in your log.

try
{
     ...
}
catch(FileNotFoundException e)
{
     ...
     throw e;    //or throw new ApplicationException(e);
}

Finally, if an exception occurs in a different AppDomain, this exception would be marshalled-by-value back and thrown in the calling AppDomain.

Further readings:

No comments: