Exception Management in Threads

Exception Management is a topic near and dear to me personally, primarily because of the lack of understanding of most developers (that I have come across). There is an interesting change in the .NET 2.0 CLR on how it manages unhandled exceptions in a thread. If you write multi-threaded apps then this is important for you to understand. If you don’t write multi-threaded apps today, but I presume you would soon, then this is a good learning exercises.

In .NET 2.0 the CLR allows unhandled exceptions in threads to proceed naturally – which in many cases probably means that the application will terminate. For certain cases (listed below) where exceptions are used for controlling program flow, the CLR does provide a backstop for unhandled exceptions in threads. Note, the CLR terminated the threads in these cases and does not propagate the exception further.

  • Abort() is called causing a ThreadAbortException.
  • AppDomain (in which the thread is running) is being unloaded, causing a AppDomainUnloadedException.
  • The Host process (or CLR) terminates the thread via an internal exception.

This is a significant change from .NET v1.x where there is no concept of a Unhandled Exception in many situations such as a Thread pool. If an unhandled exception is thrown, the runtime prints that to the console and then returns the thread to the thread pool. Also, if an unhandled exception occurs in the Start() method of a Thread class, the runtime again prints the exception stack trace to the console and then gracefully terminating the thread. Lastly, if an unhandled exception occurs on a Finalizer thread, the trace is written to the console, and the finalizer thread is allowed to resume!

Needless to say, if you have code currently designed for this, it will break in .NET 2.0 and you would need to change your implementation. As a temporary workaround you can choose your app to still use the old style from v1.x by setting the flag in the runtime section, but this should be strictly till such a time you can port the code over to the new version:

<legacyUnhandledExceptionPolicy enabled=”1″/>

If you got MSDN installed for VS 05, you can read more here then.

Published by

Amit Bahree

This blog is my personal blog and while it does reflect my experiences in my professional life, this is just my thoughts. Most of the entries are technical though sometimes they can vary from the wacky to even political – however that is quite rare. Quite often, I have been asked what’s up with the “gibberish” and the funny title of the blog? Some people even going the extra step to say that, this is a virus that infected their system (ahem) well. [:D] It actually is quite simple, and if you have still not figured out then check out this link – whats in a name?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.