[fpc-pascal] Catching exception generated by another program

Jonas Maebe jonas.maebe at elis.ugent.be
Mon Jun 15 10:54:56 CEST 2009


On 15 Jun 2009, at 07:45, leledumbo wrote:

> Suppose I have a program written in C:
>
> #include <stdio.h>
>
> int main() {
>  return 1 / 0;
> }
>
> and a Pascal program that calls it:
>
> program prog;
>
> {$mode objfpc}{$H+}
>
> uses
>  SysUtils;
>
> begin
>  try
>    ExecuteProcess('tes.exe','');
>  except
>    on e: Exception do begin
>      WriteLn(e.Message);
>    end;
>  end;
>  WriteLn('Done').
> end.
>
> How can I catch the exception generated by the C program

You cannot. Exceptions are program-local events. They do not propagate  
outside the process they are raised in (regardless of whether they are  
transformed into language-level exception objects or not).

> (note that it can be a DLL too)?

Executed via ExecuteProcess? If you mean calling a function in a dll,  
then it depends at least on the following:
1) if the dll function catches the exception itself, you won't see it  
(although if it's an FPC-compiled dll, then the exception will  
currently always propagate to the main program under Windows: http://bugs.freepascal.org/view.php?id=12974) 
, even if it reraises it afterwards (because then it will have been  
transformed from an OS-level exception into a language-level  
exception, and
a) FPC's exception model is different from that of all other  
compilers, and
b) even if the dll is compiled with FPC and if you would be able to  
catch the exception in the dll, FPC's implementation currently does  
not allow propagating language-level exceptions across dll/program  
(nor dll/dll) boundaries
b) if the dll function does not catch the exception
2) if the dll/dll function does not catch the system-level exception,  
you should be able to catch it in the FPC function that called that  
function.

> The above approach doesn't catch it. The C program terminates  
> abnormally as
> usual, and the Pascal program goes by itself (proven by string  
> 'Done' gets
> written correctly).

Most program exit with a non-zero exit code if some error occurred.  
You have to use that, or some other form of explicit communication  
(e.g., have the child process write something to a file, use some form  
of shared memory in the parent and the child, ...).


Jonas



More information about the fpc-pascal mailing list