Friday, August 5, 2022

[FIXED] How to make my FreePascal app exit with a specific code if a certain exception is thrown?

Issue

My program has an ESyntaxError class that I use like this:

raise ESyntaxError.Create(Message)

And I have that ESyntaxError class just defined like this:

ESyntaxError = class(Exception)

I observe that if that ESyntaxError.Create(Message) code has been called, my program’s exit code gets set to 1. But what I would like to have it set to instead in this case is 65.

I have tried just doing this:

ExitCode := 65;
raise ESyntaxError.Create(Message);

...But with that my app still just exits with 1, not 65—I guess because the built-in Exception class always resets ExitCode to 1? (Don’t know for sure that’s the case and have seen nothing in the Exception docs explicitly stating that, but I infer that from the behavior I’ve observed here).

Or if I want to end up with the program having a non-1/non-0 exit status, should I perhaps be handling this in some other way than basing it on Exception?


Solution

This works: you can wrap main routine in try-except block, then assign ExitCode for specific types of exceptions

program project1;

uses
  SysUtils;

type
  EMy = class(Exception);

procedure run;
begin
  raise EMy.Create('lel');
end;

begin
  try
    run;
  except
    on e: EMy do
    begin
      ExitCode := 65;
    end;
  end;
end.


Answered By - hinst
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.