Key violation Trap

Hi, I am trying to do exception handling and catch the error of a repeating field value (key violation). From my search for a solution, I saw many suggestions to catch all the errors using

try
(enter code)
except on E: EDatabaseError do
showmessage (Error message);
end; 

but I would like to respond specifically to a key violation, it uses an access table using ADO.

+3
source share
3 answers

This will work if the only error you want to handle is the message with the message "duplicate value":

try
  // Your code
except
  on E: EOleException do
  begin
    // The better way is to find out what E.ErrorCode is
    // for this specific exception, and handle it instead
    // of checking the string - you didn't provide the
    // ErrorCode, though.
    // If E.ErrorCode = <whatever> then
    //
    if Pos('duplicate value', E.Message) > 0 then
      // You've got a duplicate with the message above
      // Do whatever handles it
    else
      raise;
  end;
  // If you want to handle other exception types (eg., EDataBaseError),
  // you can do so here:
  //  on E: EDataBaseError do
  //    HandleDBError;
end;
+7
source

EDatabaseError - excption , ADO, TADOConnection.Errors, specificc Key violation, Number NativeError.

+6

, . , , , EOleException. - , , .

I suggest you check that the new identifier is not yet used before trying to add a new record. Or, as @TLama suggests, take advantage of any error-handling tools in your database infrastructure that let you plug this in before it becomes an exception.

+3
source

All Articles