RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.ExceptObject Function

Returns current exception object.

Pascal
function ExceptObject: TObject;
C++
TObject * ExceptObject();

ExceptObject returns the current exception object. This is the Exception object that represents the exception currently being handled. If no exception is currently being handled, ExceptObject returns nil (Delphi) or NULL (C++). 

ExceptObject is useful when the exception variable (declared in the Delphi on block or C++ catch statement) is not accessible. This can occur when the exception handler calls a procedure, putting the exception variable is out of scope. This is also true in the Delphi else exception handler, which cannot declare an exception variable.

Note: The object returned by ExceptObject may not exist after the exception handler finishes. Thus you cannot use ExceptObject to retain a reference to the exception object, or to re-raise the exception. If you need to do either of these things, call AcquireExceptionObject.
 

Delphi Examples: 

 

{
This example demonstrates exception handling to catch runtime
errors.
}

procedure TForm2.btIOErrorClick(Sender: TObject);
var
  ExceptionObj : TObject;
begin
  {
  Try to write something onto the console - 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, enabled the overflow
  checking and disabled optimizations because Delphi's
  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;

procedure TForm2.FormCreate(Sender: TObject);
begin

end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!