How can I catch specific exception using c# ?
In my database there is unique index on some columns.
when user inserts duplicate record this exception has been throw :
Cannot insert duplicate key row in
object ‘dbo.BillIdentity’ with unique
index ‘IX_BillIdentity’. The
statement has been terminated.
How can I catch this exception?
Currently I am checking using this code :
catch (Exception ex) {
if (ex.Message.Contains("Cannot insert duplicate key row in object 'dbo._BillIdentity' with unique index 'IX__BillIdentity")) {
string ScriptKey = "$(function() {ShowMessage('Error');});";
ScriptManager.RegisterStartupScript(Page, GetType(), "script", ScriptKey, true);
}
}
I think its bad smell code.
Is there any better way?
You haven’t shown the type of exception which is thrown, but you can catch that specific exception type. For example:
It’s possible that there won’t be a specific exception type for just this error – but if you have to catch something fairly general like
SqlExceptionyou can then look for more details within the class itself. For example inSqlExceptionthere’s anErrorsproperty where you can look at more detailed information about each of the (possibly multiple) errors at the database side. EachSqlErrorthen has aNumberproperty which will give the type of error. You can always fall back to the message if you absolutely have to, but you then need to be aware of the possibility of the message changing for different cultures etc.Note that if you’re not really handling the exception, you should probably rethrow it: