Exception handling in threads (Views: 14862)


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

<< Back to main page