Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Exception handling on it's own constructor after it is raised

The question is: after am raising an exception, can I stop it to propagate from it's own constructor? consider the code bellow:

unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TMyErrorClass = class(Exception)
    constructor Create(aMsg:String);
  end;
  TForm2 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.FormCreate(Sender: TObject);
begin
//
 raise TMyErrorClass.Create('test');
end;

{ TMyErrorClass}

constructor TMyErrorClass.Create(aMsg: String);
begin
 {$IFDEF DEBUG}
   Showmessage(aMsg);
 {$ELSE}
  //here I want to 'kill' the exception
 {$ENDIF}
end;

end.

After raise is called, how can I terminate the Exception, without adding try except/finally where I'm raising the exception?

LE: I have an app which has almost 2000 raise like this...and I'm trying to find out an alternative solution to write error handling for it....

like image 561
RBA Avatar asked Dec 27 '22 09:12

RBA


1 Answers

Once you've entered a raise statement, there are only two ways to avoid going through with raising that exception:

  • Raise something else first. From within the constructor of the exception that's about to be raised, you can create and raise a different exception first. That will avoid your program ever reaching the first raise statement.

  • Terminate the thread so nothing gets to run. You can do this various ways, including ExitThread, Halt, and ExitProcess, which are all pretty much equivalent in this context. Your program won't be running anymore, but at least you've prevented it from raising that exception!

Neither of those will solve the problem you're trying to solve, but they will do what you asked for in your question. The bottom line is that whatever you're trying to do, quelling an exception after you've already initiated the exception-raising mechanism is the wrong approach. You can't unring a bell, and you can't unraise an exception.

like image 104
Rob Kennedy Avatar answered May 06 '23 17:05

Rob Kennedy