Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 499
Ivan Prodanov Avatar asked Jul 13 '09 10:07

Ivan Prodanov


2 Answers

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; 
like image 86
Andreas Hausladen Avatar answered Oct 07 '22 01:10

Andreas Hausladen


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); 
like image 26
Marco Avatar answered Oct 07 '22 02:10

Marco