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?
Catching Specific Exceptions in PythonA try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception.
Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.
Handle SqlException
only in this case.
[Edit]
To check duplicate key exception in MS SQL server:
try { // try to insert } catch (SqlException exception) { if (exception.Number == 2601) // Cannot insert duplicate key row in object error { // handle duplicate key error return; } else throw; // throw exception if this exception is unexpected }
Edit: Where 2601 come from?
select * from sys.messages where text like 'Cannot insert duplicate key%'
Returns:
message_id language_id severity is_event_logged text ----------- ----------- -------- --------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 2601 1033 14 0 Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls.
Using exception.Number
and referencing sys.messages view you can handle any specific MS SQL exception.
You haven't shown the type of exception which is thrown, but you can catch that specific exception type. For example:
catch (DuplicateKeyException e) { ... }
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 SqlException
you can then look for more details within the class itself. For example in SqlException
there's an Errors
property where you can look at more detailed information about each of the (possibly multiple) errors at the database side. Each SqlError
then has a Number
property 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:
catch (SqlException e) { if (CheckWeCanHandle(e)) { // Mess with the ScriptManager or whatever } else { throw; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With