5

I get a Exception type using

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

so I change my code to catch that exception,

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

and the code write only "No".

How can I catch the EntityException before reach Exception?

Thanks

6
  • 2
    Are you sure that there is not other EntityException? try throw new System.Data.EntityException(); directly and see if it is caught. Commented Sep 19, 2012 at 16:37
  • 2
    try getting the type of the exception inside your second catch block, is it still EntityException? Commented Sep 19, 2012 at 16:38
  • Your code snippet must work. Tell us more information, or put the full typename together with the "No" string... Commented Sep 19, 2012 at 16:38
  • 2
    Alternatively, you can try catch(System.Data.EntityException a) Commented Sep 19, 2012 at 16:38
  • append the exception type to the end of you control string: "I got it! " + a.GetType().ToString() and e.GetType().ToString()... just to verify that when the bottom-most catch is invoked it really is getting what you believe its getting. Commented Sep 19, 2012 at 16:39

3 Answers 3

4

The code you have should work correctly, provided there isn't another EntityException type defined within the current set of using statements for that file or namespace.

Try fully qualifying the type, as in the following:

try{
...
}catch(System.Data.EntityException a){
  // need to do something
  log.Error("I got it!");
}catch(Exception e){
  log.Error("No");
}
Sign up to request clarification or add additional context in comments.

Comments

1

I was having the same problem, and the accepted answer here wasn't working for me. While EntityException is fully qualified as System.Data.EntityException, it's actually in the System.Data.Entity assembly (See http://msdn.microsoft.com/en-us/library/system.data.entityexception(v=vs.110).aspx), so the project needs a reference to System.Data.Entity before Intellisense will recognize System.Data.EntityException in your code.

1 Comment

(+1) System.Data.EntityException was not working for me either. This Question answers the same problem: Handle exceptions in entity framework 4
-1

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

1 Comment

-1 - this is exactly what OP asks - it should, but apparently does not in that particular case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.