I have a piece of try catch code:
try { ... } catch(Exception ex) { ModelState.AddModelError( "duplicateInvoiceNumberOrganisation", "The combination of organisation and invoice number must be unique"); }
For this piece of code I'm trying to insert a record into a database: The dba has set it up so that the database checks for duplicates and returns an error if there are duplicates. Currently, as you can see, I'm adding the same error to the model no matter what error occurred. I want it changed so this error is only added to the model if it was caused by the duplicate error set up by the dba.
Below is the error I want to catch. Note it's in the inner exception. Can anyone tell me how to specifically catch this one?
To get exception information from a bare exception handler, you use the exc_info() function from the sys module. The sys. exc_info() function returns a tuple that consists of three values: type is the type of the exception occurred.
The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). catch (Exception e) { if(e instanceof NotAnInt){ // Your Logic. } else if if(e instanceof ParseError){ //Your Logic. } }
Specific Exception : As you see in the example above IndexOutOfRange is handling only one type of exception hence you can say it as specific exception. Generic Exception : These Exception classes can handle any kind of exception. So can call it as generalized exception.
before your current catch add the following:
catch(DbUpdateException ex) { if(ex.InnerException is UpdateException) { // do what you want with ex.InnerException... } }
From C# 6, you can do the following:
catch(DbUpdateException ex) when (ex.InnerException is UpdateException) { // do what you want with ex.InnerException... }
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