C #, Catch Exception

I get an exception type using

catch(Exception e){
  log.Error(e.GetType()); // it write 'System.Data.EntityException'
}

so I change my code to catch this exception,

try{
...
}catch(EntityException a){
  // need to do something
  log.Error("I got it!");
}catch(Exception e){
  log.Error("No");
}

and the code only writes "No."

How can I catch an EntityException before an Exception exception?

thank

+5
source share
3 answers

The code you have should work correctly if there is no other type EntityExceptiondefined in the current statement usage set for this file or namespace.

Try to fully determine the type, as shown below:

try{
...
}catch(System.Data.EntityException a){
  // need to do something
  log.Error("I got it!");
}catch(Exception e){
  log.Error("No");
}
+4
source

, . EntityException System.Data.EntityException, System.Data.Entity(. http://msdn.microsoft.com/en-us/library/system.data.entityexception(v=vs.110).aspx), System.Data.Entity, Intellisense System.Data.EntityException .

+1

The first catch to match the exception is the one that is activated.

-1
source

All Articles