RAD Studio |  |

Handling Exceptions in the Thread Function
See Also
Collapse All

The Execute method must catch all exceptions that occur in the thread. If you fail to catch an exception in your thread function, your application can cause access violations. This may not be obvious when you are developing your application, because the IDE catches the exception, but when you run your application outside of the debugger, the exception will cause a runtime error and the application will stop running.

To catch the exceptions that occur inside your thread function, add a try...except block to the implementation of the Execute method:

Copy Code

    procedure TMyThread.Execute;
    begin
      try
        while not Terminated do
      PerformSomeTask;
      except
        { do something with exceptions }
      end;
    end;

Copy Code

    void __fastcall TMyThread::Execute()
    {
      try
      {
        while (!Terminated)
          PerformSomeTask();
      }
      catch (...)
      {
        // do something with exceptions
      }
    }

See Also

Using the Main VCL Thread

Waiting for Other Threads

Using Thread-local Variables

Checking for Termination by Other Threads

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!