I have for habit to execute anonymous thread like :
TThread.CreateAnonymousThread(
procedure
begin
.....
end).start;
But the problem is that if some unhandled exception will raise during the execution, then i will be not warned about it! For the main thread we have Application.OnException
. Do we have something similar for background thread ?
If an unhandled exception condition happens in a secondary thread and moves all the way to the first invocation in the thread without being handled, the resulting action will be to terminate the thread. During this percolation, if the exception hits a control boundary and is not handled, it may terminate the process.
You need to pass it an object that implements the Thread. UncaughtExceptionHandler interface. This interface has only one method: uncaughtException(Thread t, Throwable e). This is the method that will be called on the passed object if an uncaught exception occurs in the run method."
Finally, the primary thread can catch the current exception in a catch block and then process it or throw it to a higher level exception handler. Or, the primary thread can ignore the exception and allow the process to end.
TThread
has a public FatalException
property:
If the
Execute
method raises an exception that is not caught and handled within that method, the thread terminates and setsFatalException
to the exception object for that exception. Applications can checkFatalException
from anOnTerminate
event handler to determine whether the thread terminated due to an exception.
For example:
procedure TMyForm.DoSomething;
begin
...
thread := TThread.CreateAnonymousThread(...);
thread.OnTerminate := ThreadTerminated;
thread.Start;
...
end;
procedure TMyForm.ThreadTerminated(Sender: TObject);
begin
if TThread(Sender).FatalException <> nil then
begin
...
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With