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);
}
}
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:
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.