Solved exception handling with multiple threads

Posted on 2011-09-14
Last Modified: 2012-05-12

Was looking on internet about this but didn't see anything clear about how you should handle exceptions in multiple threads. I have an application which creates three threads which run on the same subroutine (lets call it mySub). These are created on a main thread inside a try catch block which has a finally section which cleans up any references to objects that need to be disposed of.

I'm not that familiar with threads but I know that a thread basically ends when exit sub is called or when the code completes. So, is it the case that if an error occurs in the sub on one of the three newly created threads, then I catch that error in a try catch block in mySub, and then I should throw an exception back up to the main thread? Should I use thread.abort in this try catch block in order to throw a ThreadAbortException? Well presumably I will want to throw the exception that occurred on the thread so that the main thread can read it? maybe something like the below? (I could of course be more specific with the type of exception or create my own exception type)

Then when the exception comes to the calling thread... should I terminate the other two threads at that point? Again a thread.abort? I've heard that's pretty risky... maybe it's ok if you use a begincriticalregion area to make sure it aborts in a safe place?

Thanks, Aiden

   Dim paramTS As New ParameterizedThreadStart(AddressOf mySub)
   Dim t1 As Thread = New Thread(paramTS)
Catch ex As Exception
   MsgBox("Error occurred: " & ex.ToString)
End Try

Sub mySub
      'Do work
   Catch ex As Exception
       Throw New Exception("Exception occurred")
   End Try
End Sub

Open in new window

Question by:AidenA
  • 3
  • 2
LVL 16

Expert Comment

ID: 36540730
Once a thread starts, it has a life of its own independant of what ever subroutine started it.  It will have it's own exception stack with no way to throw an exception back to the subroutine that created the thread.  After all, think about it.  In most cases, once a subroutine has started a thread, it continues doing its own processing, most likely leaving the try-catch block that started the thread, and modifying its own exception stack as it executes through other try-catch blocks.

So if there isn't a top-level try-catch block within the thread (i.e. a try-catch block for the thread's main subroutine), an unhandled exception will terminate the thread just like an unhandled exception will terminate a single threaded program.

And actually, if the main program thread terminates because of an unhandled exception, the child threads will still continue executing.  You should be able to toss together some simple test code and force some exceptions a display debug code or message boxes to prove this.

Author Comment

ID: 36542586
Hi thanks for that...

But I'm sure there must be a way of doing it? I can't believe that there is no way of knowing that an exception happened on one of your threads and finding out what that is.

Author Comment

ID: 36542604
or at least, there must be some way that if an error happens in one of your threads, you can log the error as normal... and then stop all other threads and clean up any references... how do you do that?

LVL 16

Accepted Solution

HooKooDooKu earned 500 total points
ID: 36599416
Well when it comes to thread stopping, the only way to cleaning stop threads is to set up some sort of signaling method.  Some simple examples include having global or class level variables that both threads can access.  Then one thread can flag the other to tell it to stop, or to inform another thread that the 1st thread completed.

So in the case of exception handling, you just place an exception at the top level function of the thread, and include setting some flags to indicate what has happened.

The only other thing you've got to work with is that every thread can have an exit value.  Your top-level exception handling for the thread can then return an "error" value when the thread terminates.  If you have a copy of a threads handle, their is an API function call that allows you to determine if the thread is still running or what it's exit code was.  However, to properly utilize this sort of functionality, you have to be able to start a thread in suspended mode, create a duplicate handle, then resume the suspended thread.  (If you attempt to use the thread's handle itself, there is always the possibility that the thread has finished execution and the handle no longer valid when you try to use it).

Author Comment

ID: 36599661
woah... complicated then!

I'm surprised the framework doesn't have some way of easily handling such a situation. But from what I've been reading, it does seem to get complicated as soon as you want to communicate between threads (as I saw when trying to set the progress bar on the UI from a new thread - needed delegates and whatnot)...

thanks for the info anyway, I will keep in mind

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question