Handling Exceptions in the Thread Function

From RAD Studio
Jump to: navigation, search

Go Up to Writing the Thread Function


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:

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

See Also