Ivan Prodanov
Ivan Prodanov

Reputation: 35532

How to raise exceptions in Delphi?

I'm asking for Delphi native, not Prism(net).

This is my code:

raise Exception.Create('some test');

Undeclared identifier "Exception".

Where's the problem, how do I throw/raise exceptions?

Upvotes: 30

Views: 75497

Answers (4)

Marco
Marco

Reputation: 338

Remember to add SysUtils to your uses units.

I also suggest below a nice way to keep track of categories, formats of messages and meaning of exception:

Type TMyException=class
public
  class procedure RaiseError1(param:integer);
  class procedure RaiseError2(param1,param2:integer);
  class procedure RaiseError3(param:string);
end;

implementation

class procedure TMyException.RaiseError1(param:integer);
begin
  raise Exception.create(format('This is an exception with param %d',[param]));
end;

//declare here other RaiseErrorX

A simple way of using this is:

TMyException.RaiseError1(123);

Upvotes: 13

Andreas Hausladen
Andreas Hausladen

Reputation: 8141

The exception class "Exception" is declared in the unit SysUtils. So you must add "SysUtils" to your uses-clause.

uses
  SysUtils;

procedure RaiseMyException;
begin
  raise Exception.Create('Hallo World!');
end;

Upvotes: 77

RobS
RobS

Reputation: 3857

You may need to add sysutils to the uses clause, it is not built in and is optional according to Delphi in a nutshell.

Upvotes: 7

Will
Will

Reputation: 75673

You are using SysUtils aren't you? Exception is declared in there IIRC.

Upvotes: 6

Related Questions