Author: William Gerbert
Exception handling in threads
One of my applications that ran fine on my system, particularly when run in the
Delphi IDE, started to stop executing after displaying 'Application error has
What was the reason?
I had moved I/O-depending parts of that application into separate threads in order
to increase performance and improve responsiveness of the application to user
input. It was a typical scenario, ideal for multi-threading.
It turned out that those threads threw an unexpected exception. I did have a global
exception handler as a method of my main form/ property of TApplication, but that
did not catch the exceptions raised by threads other than the main thread.
Therefore it is mandatory to do at least some basic exception handling on your
threads. The simplest solution is to put a try-except-end block in the Execute
method and silently eat all exceptions.
If you want to display the exception remember that the VCL itself is not
thread-safe. You can make it threadsafe for the execution time of a method by
calling this method with the Synchronize() function. The downside is that you
cannot pass arguments to a synchronized function. You have to pass arguments via
member variables of your thread class.
1 2 // This is the cheapest way to handle exceptions3 // in threads. if you want to display the exception4 // then you need to do this with a separate method,5 // which has to be called synchronized..6 7 procedure TSortThread.Execute;
8 begin9 try10 // do the sorting11 except12 // silently eat all exceptions13 end;