如何在dpr中捕获表单的异常

时间:2013-05-25 23:52:31

标签: delphi

我需要在Delphi 7程序中捕获所有非单元初始化异常,这样我就可以将异常写入文件,并可能向用户显示一条消息。

读到这一点,我认为全局异常处理程序会很麻烦,我只需要在DPR级别捕获所有异常。但是,我无法获得下面的代码来访问dpr中的ShowMessage。

为什么下面的Raise Exception实际上会导致屏幕上显示异常而不是弹出到.dpr的except子句?也许全局异常处理程序会是更好的方法吗?

dpr中紧接下面的代码不应该捕获表单中的所有异常吗?

在DPR中:

begin
  Application.Initialize;
  try
    Application.CreateForm(TForm1, Form1);
    Application.Run;
  except
    On E: Exception do
      ShowMessage('In dpr except. Exception is: ' + E.Message);
  end;    
end.

表格:

Function TForm1.DoSomething( out aErrm: String):boolean; // force a failure for testing
begin
  Result := FALSE;
  aErrm := 'Failed in DoSomething';
end;

procedure TForm1.FormShow(Sender: TObject); 
begin
  try
    fOk := DoSomething(fErrm);
  except
    fOk := FALSE;
    Errm := 'Unexpected exception'
  end;

  if (NOT fOk) then
    Raise Exception.Create(Errm) // why does this pop-up an exception when the DPR has an except around this code?
  else
    PostMessage(Handle, WM_CLOSE, 0, 0); // self-closing form
end;  { FormActivate }

1 个答案:

答案 0 :(得分:12)

TApplication.Run中的主消息循环包装并处理异常块中的所有消息,因此捕获所有异常,从而使DPR中的主要异常块完全无用。

如果你想捕获&处理应用程序异常,然后使用TApplication.OnException

相关问题