Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass exception from one thread to another (caller's) thread in Delphi?

I have another question! Please look at this example:

// There is a class with some method:
type
  TMyClass = class
  public
    procedure Proc1;
  end;

  // There is a some thread class:
  TMyThread = class(TThread)
  protected
    procedure Execute; override;
  end;

procedure TMyClass.Proc1;
begin
  // this method is just calling another thread:
  with TMyThread.Create(True) do
  begin
    FreeOnTerminate := True;
    Resume;
  end;
  // + there are some more actions
end;

procedure TMyThread.Execute;
begin
  // in this example this thread just throws exception:
  raise Exception.Create('Some exception');
end;

All what i want - is to get raised exception in the TMyClass.Proc1 and throw it up like this:

var
  myObject: TMyClass;
begin
  myObject := TMyClass.Create;
  try
    myObject.Proc1; // launch and watch what happenings
  except
    on E: Exception do
      WriteErrorLog(E.Message);
  end;
  FreeAndNil(myObject);
end;

Please tell me how can i make something like this? Many Thanks!

oh! one more thing - im coding on Delphi 5 so i have'nt "FatalException" property of TThread or something about..

like image 774
SomeOne Avatar asked Sep 27 '10 07:09

SomeOne


1 Answers

You can use AcquireExceptionObject():

AcquireExceptionObject returns a pointer to the current exception object and prevents the exception object from being deallocated when the current exception handler exits.

Then you can send the pointer to another thread and if you raise it there it will be freed for you, otherwise you must call ReleaseExceptionObject() to free it.

like image 64
Remko Avatar answered Sep 20 '22 13:09

Remko