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 raise Exception.Create('Bum'); except on E: Exception do begin MyHandleException(E); end; end; end; procedure TForm3.MyHandleException(AException: Exception); begin ShowMessage(AException.Message); LogThis(AException.Message); // raise AException; - this will access violate end;
So I need to re-raise it in the except block but I was wondering if there is a better way to write my own method to handle and (on specific conditions) to re-raise exceptions.
If you want to re-raise the exception only under certain conditions, write
procedure TForm3.Button1Click(Sender: TObject); begin try raise Exception.Create('Bum'); except on E: Exception do begin if MyHandleException(E) then raise; end; end; end; function TForm3.MyHandleException(AException: Exception): boolean; begin ShowMessage(AException.Message); result := true/false; end;
Following on from Craig Young's post, I've used something along the lines of the following code successfully. You can preserve the original exception location by using the "at" identifier with the ExceptAddr function. The original exception class type and information is also preserved.
procedure MyHandleException(AMethod: string); var e: Exception; begin e := Exception(AcquireExceptionObject); e.Message := e.Message + ' raised in ' + AMethod; raise e at ExceptAddr; end; try ... except MyHandleException('MyMethod'); end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With