I use asp.net 4, c# and ef4.
I would like to know what is the best way to catch an generic Exception from Entity Framework.
- At the moment I use
Exceptionit is appropriate? - How catch a more specific one?
Thanks for your time.
try
{
context.DeleteObject(myLockedContent);
context.SaveChanges();
}
catch (Exception)
{
e.Cancel = true;
}
It’s rarely good to catch generic exceptions and just cancel them. Exceptions are there to help you ensure you code can act appropriately.
You can catch specific exception types just as you have for the generic (albeit with the identifier you have missed on your example) thus:
The exception type specified in the catch statement tells the runtime to catch that specific and any child exceptions. As a result you need to organise your catch statements from the most specific exception to the least, i.e. :