文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Delphi Handle Exception

Delphi Handle Exception

时间:2011-04-15  来源:潺缘

初在Delphi里进行处理错误时,最常用的做法是try….except ….end. 例如:

try
    raise Exception.Create('Error Message');
  except
    on e:Exception do
    begin
      ShowMessage(e.Message);
    end;

  end;

 

而现在要说的是另外的一种做法:

var
  ExceptionObj : TObject;
begin
  { Simulate an access violation. }
  try
    System.Error(reAccessViolation);
  except
    ExceptionObj := ExceptObject;
    if ExceptionObj <> nil then
    begin
      MessageDlg(ExceptionObj.ToString, mtError, [mbOK], 0);
    end;
  end;
end;

在上面的代码,使用了ExceptObject这个对象,这个对象是在System单元中定义的,用于返回当前正在处理的错误对象,如果没有发生错误,其值为nil。当错误变量(在try..except里定义的)不可访问时,ExceptObject就显得很有用,例如当错误处理代码调用一个函数进行错误处理时。

需要注意的是,当错误处理完毕后,ExceptionObject返回的将是nil。还有可能会用到的一个函数是AcquireExceptionObject。这个函数返回当前except 对象的指针,这个函数的作用是为了防止当前的except对象被释放掉。AcquireExceptionObject是通过引用计数进行操作的。

 

下面是delphi的错误处理的代码:

procedure TForm2.btIOErrorClick(Sender: TObject);
var
  ExceptionObj : TObject;
begin
  {
  Try to write something onto the console--it will raise an
  exception.
  }
  try
  WriteLn('This will generate an error because there is no' +
          ' console attached!');
  except
    ExceptionObj := ExceptObject;
    if ExceptionObj = nil then
      MessageDlg('No exception', mtError, [mbOK], 0)
    else
    begin
      MessageDlg(ExceptionObj.ToString, mtError, [mbOK], 0);
    end;
  end;
end;
 
{$OVERFLOWCHECKS ON}
{$OPTIMIZATION OFF}
{$HINTS OFF}
procedure TForm2.btOverflowErrClick(Sender: TObject);
var
  b : Cardinal;
  ExceptionPtr : Pointer;
begin
  {
  Simulate an overflow. Note: Enable the overflow
  checking and disable optimizations, because the Delphi
  compiler will not compile this code otherwise.
  }
  ExceptionPtr := nil;
  try
    b := $FFFFFFFF;
    b := b * b;
  except
    ExceptionPtr := AcquireExceptionObject;
  end;
 
  // Check exception.
  if ExceptionPtr = nil then
    MessageDlg('No exception', mtError, [mbOK], 0)
  else
  begin
    MessageDlg(TObject(ExceptionPtr).ToString, mtError, [mbOK], 0);
    ReleaseExceptionObject;
  end;
end;
{$HINTS ON}
{$OPTIMIZATION ON}
{$OVERFLOWCHECKS OFF}
 
procedure TForm2.btRuntimeErrorClick(Sender: TObject);
var
 
  ExceptionObj : TObject;
  begin
  { Simulate an access violation. }
  try
    System.Error(reAccessViolation);
  except
    ExceptionObj := ExceptObject;
    if ExceptionObj = nil then
      MessageDlg('No exception', mtError, [mbOK], 0)
    else
    begin
      MessageDlg(ExceptionObj.ToString, mtError, [mbOK], 0);
    end;
  end;
end;
 
相关阅读 更多 +
排行榜 更多 +
斗虫公园手机版下载

斗虫公园手机版下载

休闲益智 下载
武林外传之同福奇缘手机版下载

武林外传之同福奇缘手机版下载

角色扮演 下载
无畏契约源能行动小米服手游下载

无畏契约源能行动小米服手游下载

飞行射击 下载