C # exception handling with Entity 4 framework

I am using asp.net 4, c # and ef4.

I would like to know what is the best way to catch a general Exception from the Entity Framework.

  • I'm currently using Exception, is this suitable?
  • How to catch more specific?

Thank you for your time.

try
{
    context.DeleteObject(myLockedContent);
    context.SaveChanges();
}
catch (Exception)
{
    e.Cancel = true;
}
+3
source share
3 answers

It is rare to catch common exceptions and simply undo them. There are exceptions to help you ensure that your code can act accordingly.

You can catch certain types of exceptions in the same way as for the general one (albeit with the identifier that you missed in your example):

catch (OptimisticConcurrencyException ex) 
{
    // Do some real work to resolve the exception
}

, catch, . , ..

catch (OptimisticConcurrencyException ex) 
{
    // Do some real work to resolve the specific exception
}
...
catch (Exception ex) 
{
    // Do some real work to resolve the generic 'catch-all' exception
}
+7

.

, . , , , .

, , , . , , .

catch all

a) ( ).

b), ( , ).

, , . , , , , .

+5

, , , - , , SMTPAppender, Log4Net .

That being said, it really depends on whether you want to handle different exceptions differently, for example, if the file was not found, you can decide to create it or say that the user did something, if you selected a more general exception, you you can act differently ...

just keep in mind that you have to put all your catch clauses from more specific to more general, in your example, if you have several catches, the one you wrote should be placed at the end.

+2
source

All Articles