Skip to content
Advertisement

Is it OK to swallow an exception for DB INSERT

Is it OK to swallow Duplicate key violation exceptions for INSERTS or should you check if the record exists?

So let’s say that I have a table Photo with one field: PhotoName. I’m looking through a file directory to add items to Photo. In the process, it’s possible that when I find a photoname, it might already be in the database. So there are two ways to go about this:

On the one hand, I don’t necessarily like the notion of just “swallowing” an exception, but on the other hand, try…catch uses only one call to the DB. This happens to be in SQL Server.

Advertisement

Answer

You should definitely not just “swallow” the exception. You should be trying to find these duplicates and not insert them if needed.

On method could be checking where not exists on the key.

This method will allow you to only INSERT new rows into the table. This method of course does not account for any matching you may need to do for an UPDATE, however that’s outside the scope of this question but should still be thought about. Most users could also use MERGE I’ll post an example of that when I get time.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement