你知道在Delphi代码中捕获、记录和重新引发异常的方法吗?一个简单的例子:
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;
所以我需要在except块中重新引发它,但我想知道是否有更好的方法来编写我自己的方法来处理和(在特定条件下)重新引发异常。
发布于 2010-05-28 01:29:03
如果只想在某些情况下重新引发异常,请编写
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;
发布于 2012-05-03 13:15:40
在Craig Young的帖子之后,我已经成功地使用了以下代码。您可以通过在ExceptAddr函数中使用"at“标识符来保留原始异常位置。原始异常类类型和信息也会被保留。
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;
发布于 2010-05-28 01:15:09
您应该能够仅使用Raise
命令本身来重新引发异常:
begin
MyHandleException(E);
Raise;
end;
https://stackoverflow.com/questions/2923230
复制相似问题