How should I re-raise a Delphi exception after logging it?

前端 未结 8 1307
攒了一身酷
攒了一身酷 2021-01-01 10:40

Do you know a way to trap, log, and re-raise exception in Delphi code? A simple example:

procedure TForm3.Button1Click(Sender: TObject);
begin
  try
    rais         


        
8条回答
  •  滥情空心
    2021-01-01 11:35

    The following will work, but is of course not ideal for 2 reasons:

    • The exception is raised from a different place in the call stack.
    • You don't get an exact copy of the exception - especially those classes that add attributes. I.e. you'll have to explicitly copy the attributes you need.
    • Copying custom attributes can get messy due to required type checking.

    .

    procedure TForm3.MyHandleException(AException: Exception);
    begin
      ShowMessage(AException.Message);
      LogThis(AException.Message);  
      raise ExceptClass(AException.ClassType).Create(AException.Message);
    end;
    

    The benefits are that you preserve the original exception class, and message (and any other attributes you wish to copy).

    Ideally you'd want to call System._RaiseAgain, but alas that is a 'compiler-magic' routine and can only be called by raise;.

提交回复
热议问题