5

I have background threads in my application. When one of the threads gets an exception that is not handled the entire CLR exits.

Is it normal behavior, or is it a bug in the CLR?

I would expect that the thread will exit but the CLR will continue working.

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
ofer alper
  • 71
  • 3

4 Answers4

7

The default behavior in .NET applications is to exit whenever an unhandled exception occurs. When an exception goes unhandled, the program is in an unknown and possibly unsteady state. Just because it happened in a background thread doesn't mean that the error won't affect the rest of the program. The most prudent course for the runtime in that situation is to dump the program.

You might look into AppDomain.CurrentDomain.UnhandledException, which will allow you to catch unhandled exceptions and react accordingly. A better solution is to wrap your thread proc with a try...catch. But only have it handle those exceptions it knows how to handle. Doing this:

void MyThreadProc()
{
    try
    {
        // ... 
    }
    catch
    {
        // handle all exceptions
        // This is a BAD idea
    }
}

Is a really bad idea, because it can mask exceptions that you really do want to be propagated to the main program.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
4

Your expected behavior used to be the behavior back in 1.1. It was generally considered to have been a bad idea. When you have an unhandled exception in any thread, your process can be left in an inconsistent state. Updates to shared data may be partially applied, etc. The runtime doesn't have the information to safely handle this scenario, or even know how you want to handle this scenario, so its choice would amount to terminating the thread and leaving your program in a strange state. This could lead to resource leaks, hangs, corruption of data, etc. By terminating the process given an unhandled exception you know exactly what happens, the process ends.

Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78
1

This is a normal behavior of the CLR from v2.0. Here is a MSDN post on this. To avoid process from terminating you could use something like this

<legacyUnhandledExceptionPolicy enabled="1"/>

which is not advisable.

Naveen
  • 4,092
  • 29
  • 31
0

It is normal behavior. Perhaps you want to catch the exception to prevent the application from exiting.

Kit
  • 20,354
  • 4
  • 60
  • 103
Kris Ivanov
  • 10,476
  • 1
  • 24
  • 35