RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.GetLastError Function

Returns the last error reported by an operating system API call.

Pascal
function GetLastError: Integer; stdcall;
C++
__stdcall int GetLastError();

GetLastError returns the last error reported by an API call into the operating system. Calling this function usually resets the operating system error state.  

C++ Examples: 

 

//
//This code demonstrates the use of system error codes
//and how to use transform them into C++ exceptions.
//
void __fastcall TForm2::btRaiseLastClick(TObject *Sender)
{
    /* Set the last OS error to a bogus value */
    System::SetLastError(ERROR_ACCESS_DENIED);

    try
    {
        RaiseLastOSError();
    }
    catch(EOSError* ex)
    {
        MessageDlg(String("Caught an OS error with code: ") +
            IntToStr((int)ex->ErrorCode), mtError,
            TMsgDlgButtons() << mbOK, 0);
    }


    /* Let the Delphi's Exception dialog pop-up */
    RaiseLastOSError(ERROR_NOT_ENOUGH_MEMORY);

    /* Finally set the last error to none */
    System::SetLastError(ERROR_SUCCESS);

    if (GetLastError() != ERROR_SUCCESS)
        MessageDlg(String("Whoops, something went wrong ") +
          " in the mean time!", mtError, TMsgDlgButtons() << mbOK, 0);

    /* No exception should be thrown here */
    RaiseLastOSError();
}

 

Delphi Examples: 

{
This code demonstrates the use of system error codes
and how to transform them into Delphi exceptions.
}
procedure TForm2.btRaiseLastClick(Sender: TObject);
begin
  { Set the last OS error to a bogus value }
  System.SetLastError(ERROR_ACCESS_DENIED);

  try
    RaiseLastOSError();
  except
    on Ex : EOSError do
       MessageDlg('Caught an OS error with code: ' +
          IntToStr(Ex.ErrorCode), mtError, [mbOK], 0);
  end;

  { Let the Delphi's Exception dialog pop-up }
  RaiseLastOSError(ERROR_NOT_ENOUGH_MEMORY);

  { Finally set the last error to none }
  System.SetLastError(ERROR_SUCCESS);

  if GetLastError() <> ERROR_SUCCESS then
     MessageDlg('Whoops, something went wrong in the ' +
                'mean time!', mtError, [mbOK], 0);

  { No exception should be thrown here }
  RaiseLastOSError();
end;

 

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