Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when a .NET thread throws an exception?

We have an interface IPoller for which we have various implementations. We have a process that will take an IPoller and start it in a separate thread. I'm trying to come up with a generic way of providing exception handling for any IPollers which don't do it themselves.

My original thinking was to create an implementation of IPoller that would accept an IPoller and just provide some logging functionality. The question I ran into though is how would I provide this error handling? If I have IPoller.Start() which is the target for the Thread is that where the exception will occur? Or is there something on the thread itself I can hook into?

like image 979
Shane Courtrille Avatar asked Nov 03 '09 16:11

Shane Courtrille


People also ask

What happens if there is exception in thread?

An uncaught exception will cause the thread to exit. When it bubbles to the top of Thread. run() it will be handled by the Thread's UncaughtExceptionHandler. By default, this will merely print the stack trace to the console.

Can thread throw an exception?

To be able to send the exception to the parent thread, you can put your background thread in a Callable (it allows throwing also checked exceptions) which you then pass to the submit method of some Executor.

Does An exception occurred in one thread causes other threads to terminate?

Usually - no, exception in one thread does not kill another thread; unless....


2 Answers

You should catch the exception at the method you use at the top of the thread, and do the logging from there.

An unhandled exception (at the top of a thread) will (in 2.0 onwards) kill your process. Not good.

i.e. whatever method you pass to Thread.Start (etc) should have a try/catch, and do something useful in the catch (logging, perhaps graceful shutdown, etc).

To achieve this, you could use:

  • static logging methods
  • captured variables into the delegate (as an anonymous method)
  • expose your method on an instance that already knows about the logger
like image 32
Marc Gravell Avatar answered Sep 26 '22 05:09

Marc Gravell


Something like:

Thread thread = new Thread(delegate() {
    try
    {
        MyIPoller.Start();
    }
    catch(ThreadAbortException)
    {
    }
    catch(Exception ex)
    {
        //handle
    }
    finally
    {
    }
});

This will ensure the exception doesn't make it to the top of the thread.

like image 190
Rex M Avatar answered Sep 24 '22 05:09

Rex M