Alex Rivera | Logout

Catching specific exception

Asked 2011-05-25T06:31:14.580
32

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?

Edit
Report

1 Answer

-1

You could only catch the SqlException for starters

catch (SqlException 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);
    }
}
answered 2011-05-25T06:33:32.940

Your Answer