How to put db_merge into a try catch?
A merge query does this:


Does a record with the provided keys already exist in the database?
If no, add it with the provided field values
If yes, update the existing record with the provided field values.


Finding a duplicate isn't considered an exceptional circumstance, because that's what the query is designed to do; so no exception will be thrown.

If your aim is to support this statement:

"you can't add this record because it exists in the db"


Then a merge query might not be the right tool. db_insert() in a try...catch might make more sense in that case.

If you just want to know whether a record was added or updated, check the return value from MergeQuery::execute():

$result = $query-&gt;execute();
switch ($result) {
  case MergeQuery::STATUS_INSERT:
    // New record was added
    break;
  case MergeQuery::STATUS_UPDATE:
    // Existing record was updated
    break;
}