Threads and runtime errors

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Threads and runtime errors

Carsten Bager
In the small threads program below I force a runtime error in a thread.
How do I get access to the output from the thread when it stops?
This program does not write anything to the terminal when the thread stops.

Carsten



-------------------------------------------------------
program testthreads;
{$mode objfpc}
{$RANGECHECKS ON}
{$OVERFLOWCHECKS ON}
{$S+ STACK CHECKING ON}
{$SMARTLINK ON}
{$TYPEINFO ON}
{$LONGSTRINGS OFF}

uses
  cthreads,
  sysutils,
  classes;

type
  TMyThread=class(TThread)
  private
    ch : char;
  protected
    procedure Execute; override;
  public
    constructor Create(c:char);
  end;

procedure TMyThread.Execute;
var
  p:integer;
begin
  repeat
    writeLn(ch);
    sleep(5000);
    p:=0;
    if ch='a' then
      p:=p div p;
  until Terminated;
end;


constructor TMyThread.Create(c:char);
begin
  ch:=c;
  inherited Create(false);
end;

var
  t1,t2 : TMyThread;
begin
  t1:=TMyThread.Create('a');
  t2:=TMyThread.Create('b');
  readln;
  t2.Terminate;
  readln;
  t1.Terminate;
  readln;
  t2.Destroy;
  t1.Destroy;
end.

_______________________________________________
fpc-pascal maillist  -  [hidden email]
http://lists.freepascal.org/mailman/listinfo/fpc-pascal
Reply | Threaded
Open this post in threaded view
|

Re: Threads and runtime errors

Vinzent Höfler
On Friday 22 June 2007 06:27, Carsten Bager wrote:
> In the small threads program below I force a runtime error in a
> thread. How do I get access to the output from the thread when it
> stops? This program does not write anything to the terminal when the
> thread stops.

In case a runtime error occurs, the thread object stores the exception
which occured, so before destroying the threads try something like:

|if Assigned (t1.FatalException) do
|   WriteLn (StdErr, t1.FatalException.ClassName,
|                    t1.FatalException.Message);

Alternatively you can embrace the Execute method with a try-except
statement.


Regards,

Vinzent.

_______________________________________________
fpc-pascal maillist  -  [hidden email]
http://lists.freepascal.org/mailman/listinfo/fpc-pascal