RuntimeErrors (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demostrates the use of ErrorProc and how to catch run-time errors.

Code

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--
    it 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: Enable the overflow checking and disable optimizations, 
    because the Delphi 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;

Uses

Personal tools
Assistance