Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch unhandled exception that are raised in background thread?

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 ?

like image 491
zeus Avatar asked Sep 18 '18 15:09

zeus


People also ask

How do you handle an unhandled exception in the 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.

How can you catch an exception thrown by another thread in Java?

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."

Which thread can catch an exception thrown in a thread?

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.


1 Answers

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 sets FatalException to the exception object for that exception. Applications can check FatalException from an OnTerminate 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;
like image 94
Remy Lebeau Avatar answered Nov 14 '22 19:11

Remy Lebeau