user496949
user496949

Reputation: 86065

exception handling in the multi thread environment

I want to know if

try/catch can catch the exceptions thrown by the children threads.

if not, what's the best practice to handling exceptions thrown in the child thread.

Upvotes: 3

Views: 4420

Answers (3)

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

You can listen to the Application.ThreadException and AppDomain.UnhandledException events to catch uncaught exceptions from thread. But the best is to catch and handle exceptions in the threads themselves. This should be a last resort for graceful shutdown / logging.

Upvotes: 6

Simone
Simone

Reputation: 11797

It depends on the .NET framework you're targeting.

In 1.1 and lesser, exceptions thrown by children threads will be forwarded to the main thread only if they run outside a try/catch block.

In 2.0 and later, this behaviour is changed: thread will be terminated and exceptions won't be allowed to proceed any further.

Anyway, you can handle exceptions inside a thread as you would do in a single-threaded application.

See http://msdn.microsoft.com/en-us/library/ms228965(v=VS.90).aspx for reference.

Upvotes: 3

Cheng Chen
Cheng Chen

Reputation: 43513

No, consider the following code:

try
{
   var t = new Thread(()=>
      {
          Thread.Sleep(5000);
          throw new Exception();
      });
   t.Start();
   //t.Join();
}
catch
{
    //you can't deal with exception here
    //even though you uncomment `t.Join`
}

Deal with exceptions in the child thread which the exceptions "belongs" to.

Upvotes: 1

Related Questions