Using and trying catch in C # database related classes?

Does it use catch keywords or handle exceptions in C # when connecting to a database? Or should I use a try catch block in all my database methods inside use? Is using try catch using unnecessary code?

using (var db = new ApplicationContext())
{        
    try {
       /* Query something */
    } catch(Exception e) {
       logger.Debug(e);
    }
}  

      

+3


source to share


5 answers


Does it use catch keywords or handle exceptions in C # when connecting to a database?

A is using

logically equivalent to a try-finally

, so yes, it handles exceptions, but that doesn't stop the exception. A finally

propagates the exception.

Should I use a try catch block in all my database methods inside use?

No . The try-catch attempt must go out of bounds using

. Thus, it will protect the creation of resources.

Is using try catch using unnecessary code?

I don't know what this question means.

Some questions you didn't ask about:

Should I catch all logging exceptions and then not rethrow them?



No . Only catch and there are exceptions that you know how to handle. If you want to log exceptions, then rethrow them when you're done recording; other code might want to handle them.

What is the correct way to write this code?

Share your concerns . You have three problems:

  • Dispose of the resource
  • Log all exceptions
  • Handling Expected Exogenous Exceptions

Each of them must be processed in a separate expression:

try // handle exogenous exceptions
{  
   try // log all exceptions
   {
       using(var foo = new Foo()) // dispose the resource
       {
           foo.Bar();
       }
   }
   catch(Exception x)
   {
       // All exceptions are logged and re-thrown.
       Log(x);
       throw;
   }
}
catch(FooException x) 
{
    // FooException is caught and handled
}

      

If your only goal is to log unhandled exceptions, then invert the nesting of the two handlers, or use a different mechanism such as the appdomain unhandled exception event handler.

+8


source


The block using

does not "handle" the exception for you, it only ensures that the method Dispose()

is called on the object IDisposable

(in this case, your instance db

) even in the event of an exception. So yes, you need to add blocks try-catch

where necessary.

However, in general, you only want to catch exceptions where you can actually do something meaningful with them. If you only need to log exceptions, consider making the exception handling one place higher in the call stack so you don't have to lure your code in blocks try-catch

all over the place.

You can read about Using Statement here to see what it actually does and how it translates.

EDIT:



If for any reason you choose to keep your block try-catch

where it is, at least make sure to reverse engineer the exception rather than swallowing it, which would be like sweeping the mess under the rug and pretending to be fine. Also, make sure to restore it without losing your precious stack trace. Like this:

using (var db = new ApplicationContext())
{        
    try {
       /* Query something */
    } catch(Exception e) {
       logger.Debug(e);
       throw; // rethrows the exception without losing the stack trace.
    }
}

      

EDIT 2 : Very good blog post by Eric Lippert on exception handling .

+8


source


Your using

converts to below code C # compiler, 8.13 using statement :

{
    var db = new ApplicationContext();
     try
     {
       try {
          /* Query something */
       } catch(Exception e) {
          logger.Debug(e);
       }
     }
     finally
     {
       // Check for a null resource.
       if (db!= null)
        // Call the object Dispose method.
           ((IDisposable)myRes).Dispose();
     }
}

      

So my opinion, for your situation, I think it's better without instruction using

, it will be a little clear and will have fewer steps:

 var db = new ApplicationContext();
 try
 {
    /* Query something */                  
 }
 catch(Exception e)
 {
    logger.Debug(e);
 }
 finally
 {
    if (db!= null)
    {
      ((IDisposable)myRes).Dispose();
    }
 }

      

Because it using

's just syntactic sugar.

PS: The operator execution cost is try

very small and you can leave your code as it is.

+3


source


The use keyword is used to ensure that after the block finishes, the object within the use parameter, in this case the context, is properly disposed of, and so yes, you still need to use try-catch keywords to handle exceptions.

+1


source


Since it using

does not handle any exceptions, you might want to swap.

using

is syntactic sugar for try-finally

, so you know that even if the exception is not handled by the constructor, the connection will either be closed or not established at all.

try {
    using (var db = new ApplicationContext())
    {        

       /* Query something */

    }  
} catch(Exception e) {
   logger.Debug(e);
}

      

+1


source







All Articles