Board index » delphi » Key violation handling

Key violation handling


        I am a novice programmer who is writing a small database
program and I have run into a snag.  I have set up a single field
lookup table that the user will populate.  I have keyed the table so
that there are no duplicate entries.  When I run the program and
purposely enter a duplicate value in the table, I get a Key Violation
error and it locks the program up.  My intention was to test the value
of the entry with the SetKey method and prevent posting the record
until the entry became unique.  Unfortunately, as soon as I hit enter
the program locks up before the code I wrote executes.  Is there any
way around this?  (disabling the enter/post property of the DBEdit
object for example?)  Any advice would be appreciated.

Thanks in advance,



Re:Key violation handling

I solve key violation errors by trapping the exception.  The procedure is
as follows:

Declare an exception handler as private.

   procedure MyException(Sender: TObject; E: Exception);

Take over the exception handler in FormCreate.

   Application.OnException := MyException;

Release the exception handler in FormClose.

   Application.OnException := Nil;

Implement the new exception handler.

procedure TMyForm.MyException(Sender: TObject; E: Exception);
   if  E is EDBEngineError then
      if E.Message = 'Key violation' then
         MessageDlg(Format('Duplicate Key [%s]',
           [MyTableMyKeyField.Value]), mtError, [mbOK], 0);


Other Threads