unit LastOSError_unit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm2 = class(TForm)
    btRaiseLast: TButton;
    procedure btRaiseLastClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

// BeginExample: LastOSError
// Routine: SysUtils.RaiseLastOSError
// Routine: System.SetLastError
// Routine: System.GetLastError

// BeginCode
{
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;
// EndCode
// EndExample: LastOSError

end.
