3

Does using keyword catch or handle exceptions in C# when connecting to a database? Or should I use try catch block in all of my database methods inside the using? Does using try catch create unnecessary code?

using (var db = new ApplicationContext())
{        
    try {
       /* Query something */
    } catch(Exception e) {
       logger.Debug(e);
    }
}  
Joni Turunen
  • 137
  • 1
  • 13
  • 1
    no using does not catch any exceptions. it is used to properly dispose the object – apomene Jul 01 '15 at 13:10
  • using and try...catch are two different things – Roman Marusyk Jul 01 '15 at 13:11
  • 1
    As an aside, you shouldn't generally catch `Exception` - only catch exceptions for which your code has a clear way of dealing with them. Leave everything else to an outermost unhandled exception handler that will (finally) log the error and then shut down the application. – Damien_The_Unbeliever Jul 01 '15 at 13:12
  • [using](https://msdn.microsoft.com/library/aa664736.aspx) basically creates a `try...finally`. *No* `catch`! – Corak Jul 01 '15 at 13:13
  • Guess this will answer the first question http://stackoverflow.com/questions/149609/c-sharp-using-syntax – HarryQuake Jul 01 '15 at 13:17

5 Answers5

8

The using block does not "handle" exceptions for you, it only ensures that the Dispose() method gets called on the IDisposable object (in this case, your db instance), even in the event of an exception. So yes, you need to add try-catch blocks where needed.

That said, in general, you only want to catch exceptions where you can actually do something meaningful with them. If you only need to log the exceptions, consider doing your exception handling in a single location higher in the call stack so that you don't have to litter your code with try-catch blocks all over the place.

You can read about the using Statement here to see what it actually does, and how it gets translated.

EDIT:

If, for whatever reason, you choose to keep your try-catch block where it is, at the very least, make sure to rethrow the exception instead of swallowing it, which would be like sweeping the mess under the rug and pretending everything is fine. Also, make sure to rethrow 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 nice blog entry by Eric Lippert about exception handling.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
sstan
  • 35,425
  • 6
  • 48
  • 66
8

Does using keyword catch or handle exceptions in C# when connecting to a database?

A using is logically equivalent to a try-finally, so yes, it handles exceptions, but it does not stop the exception. A finally propagates the exception.

should I use try catch block in all of my database methods inside the using?

No. The try-catch should go outside the using. That way it will protect the resource creation.

Does using try catch create unnecessary code?

I have no idea what this question means.

Some questions you did not ask:

Should I catch all exceptions for logging and then fail to re-throw them?

No. Only catch and eat exceptions that you know how to handle. If you want to log exceptions then re throw them when you're done logging; other code might want to handle them.

What is the correct way to write this code?

Separate your concerns. You have three concerns:

  • Dispose the resource
  • Log all exceptions
  • Handle expected exogenous exceptions

Each of those should be handled by a separate statement:

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 goal is to only log unhandled exceptions then invert the nesting of the two handlers, or use another mechanism such as the appdomain's unhandled exception event handler.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
3

Your using will converts to bottom code by the C# compiler, by 8.13 The 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's Dispose method.
           ((IDisposable)myRes).Dispose();
     }
}

So, my opinion, for your situation I think better without using statement, it will be a little bit clear and will have less steps:

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

Because using it's just a syntax sugar.

P.S: The performance cost of try statement is very small and you can left your code as it is.

ivamax9
  • 2,601
  • 24
  • 33
1

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

AllFallD0wn
  • 551
  • 7
  • 23
1

Since using does not handle any exception, you may want to swap.

using is syntactic sugar for try-finally so you know that, even if exception is not handled on constructor, connection will be either closed or not established at all.

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

       /* Query something */

    }  
} catch(Exception e) {
   logger.Debug(e);
}
usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305