Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if an exception is of a particular type

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?

enter image description here

like image 947
AnonyMouse Avatar asked Feb 14 '12 00:02

AnonyMouse


People also ask

How does Python determine exception type?

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.

How can I tell if an instance of an exception is available?

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. } }

What is the difference between a specific exception and a general exception?

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.


1 Answers

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... } 
like image 138
Davide Piras Avatar answered Oct 15 '22 20:10

Davide Piras