如何将异常处理的代码放在Delphi异常处理程序中?

时间:2020-05-21 07:35:09

标签: delphi exception

我正在编写一个错误处理程序,试图修复或减轻错误。如果缓解代码错误,我想忽略缓解错误并提出原始错误。这是我编写的错误处理程序。

try
  // <Normal code>
  raise Exception.Create('Original error');
except
  on E: Exception do
  try
    // <Attempt to mitigate the error>  // If successful will continue without an exception
    raise Exception.Create('Mitigation error'); 
  except
    raise E;  // Mitigation failed, raise original error
  end;
end;

以上操作无效。当缓解异常触发时,应用程序陷入混乱的无效指针中。

有人知道该怎么做吗?

1 个答案:

答案 0 :(得分:2)

try
  // <Normal code>
  raise Exception.Create('Original error');
except
  on E: Exception do
  try
    // <Attempt to mitigate the error>  // If successful will continue without an exception
    raise Exception.Create('Mitigation error'); 
  except
    raise E;  // Mitigation failed, raise original error
  end;
end;

一旦处理了异常,它将在处理该异常的except块的末尾销毁。但是,您执行raise E会将异常传播到该块之外以及其使用寿命结束。

如果希望使用re-raise an exception, and thus prolong its life beyond the block which handles it,则需要使用未经修饰的raise语法。但是,您不能在嵌套的except块内执行此操作,因为这将涉及缓解错误。相反,您需要在外部raise块中编写except

procedure Foo;
var
  MitigationSucceeded: Boolean;
begin
  try
    // <Normal code>
    raise Exception.Create('Original error');
  except
    on E: Exception do
    begin
      try
        MitigationSucceeded := True;
        // <Attempt to mitigate the error>  // If successful will continue without an exception
        raise Exception.Create('Mitigation error');
      except
        // using raise here would refer to mitigation error ...
        MitigationSucceeded := False;
      end;

      if not MitigationSucceeded then
        // ... but used here it is the original error
        raise;
    end;
  end;
end;