Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 820
Nik Todorov Avatar asked May 27 '10 17:05

Nik Todorov


2 Answers

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; 
like image 74
Andreas Rejbrand Avatar answered Sep 23 '22 20:09

Andreas Rejbrand


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; 
like image 29
Wes Avatar answered Sep 22 '22 20:09

Wes