Java – thesql unique index used as exception handling method in java


I want to know whether is it a good idea to catch exception based on unique index of sql in java.

i want to catch an exception like 'duplicate entry for 1-0' if so then handle exception otherwise insert properly in database table?

Best Solution

I say you don't do that, for two reasons:

  • the error messages are a bit unclear: ERROR 1062 (23000): Duplicate entry 'xxx' for key 1. Are you always 100% sure which key is 1?
  • it locks in you to a specific database vendor

I find it simpler to transactionally:

  • check for row's existence;
  • throw an exception if the row already exists;
  • insert the new row.

Performance issues:

I say measure twice, cut once. Profile the usage for your specific use case. Top of my head I would say that the performance will not be an issue except for the heavy db usage scenarios.

The reason is that once you perform a SELECT over that specific row, its data will be placed in the database caches and immediately used for insertion check done on the index for the INSERT statement. Also keeping in mind that this access is backed by an index leads to the conclusion that performance will not be an issue.

But, as always, do measure.