unit ExceptionHandling_unit;

interface

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

type
  TForm2 = class(TForm)
    btRuntimeError: TButton;
    btIOError: TButton;
    btOverflowErr: TButton;
    procedure FormCreate(Sender: TObject);
    procedure btRuntimeErrorClick(Sender: TObject);
    procedure btIOErrorClick(Sender: TObject);
    procedure btOverflowErrClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

// BeginExample: ExceptionHandling
// Routine: System.AcquireExceptionObject
// Routine: System.ExceptObject

// BeginCode
{
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;

// EndCode
// EndExample: ExceptionHandling

end.
