unit RuntimeErrors_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: RuntimeErrors
// Routine: System.Error
// Variable: System.ErrorProc
// Type: System.TRuntimeError

// BeginCode
{
This example demostrates the use of ErrorProc and how to catch runtime
errors.
}
procedure MyErrorProc(ErrorCode : Byte; ErrorPtr : Pointer);
var
  ErrorName : String;
begin
  { Get the "name" of the enum value using RTTI }
  ErrorName := GetEnumName(TypeInfo(TRuntimeError), ErrorCode);

  { Show an error box }
  MessageDlg(Format('Error with code %d (%s) risen at $%X.',
      [ErrorCode, ErrorName, Integer(ErrorPtr)]), mtError, [mbOK], 0);
end;

procedure TForm2.btIOErrorClick(Sender: TObject);
begin
  {
  Try to write something onto the console - will raise an
  exception.
  }
  WriteLn('This will generate an error because there is no' +
          ' console attached!');
end;

{$OVERFLOWCHECKS ON}
{$OPTIMIZATION OFF}
{$HINTS OFF}
procedure TForm2.btOverflowErrClick(Sender: TObject);
var
  b : Cardinal;
begin
  {
  Simulate an overflow: Note, enabled the overflow
  checking and disabled optimizations because Delphi's
  compiler will not compile this code otherwise.
  }
  b := $FFFFFFFF;
  b := b * b;
end;
{$HINTS ON}
{$OPTIMIZATION ON}
{$OVERFLOWCHECKS OFF}

procedure TForm2.btRuntimeErrorClick(Sender: TObject);
begin
  { Simulate an access violation }
  System.Error(reAccessViolation);
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  { Register my System error proc }
  ErrorProc := MyErrorProc;
end;

// EndCode
// EndExample: RuntimeErrors

end.
