DelphiFAQ Home Search:
General :: Windows :: Programming :: Windows with Delphi :: Windows API
Windows programming with Delphi


This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Only the 40 most recently viewed articles are shown.
You can see the full list here.

Featured Article

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 occurred'.
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.

// This is the cheapest way to handle exceptions
// in threads. if you want to display the exception
// then you need to do this with a separate method,
// which has to be called synchronized..

 procedure TSortThread.Execute;
     // do the sorting
     // silently eat all exceptions
You don't like the formatting? Check out SourceCoder then!
Generated 16:02:03 on Jul 12, 2020