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

前端 未结 8 1249
攒了一身酷
攒了一身酷 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:33

    Old topic but, what about this solution?

    procedure MyHandleException(AException: Exception);
    begin
      ShowMessage(AException.Message);
      AcquireExceptionObject;
      raise AException;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      try
        raise Exception.Create('Bum');
      except
        on E: Exception do
          MyHandleException(E);
      end;
    end;
    

    It's based on the first code posted by Eduardo.

    0 讨论(0)
  • 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;.

    0 讨论(0)
提交回复
热议问题