Wednesday, December 31, 2014

Where to use the try/catch block in a using to catch exceptions?

I have this code:



using(MyEntities dbContext = new MyEntities)
{
//myCode
}

Well, the using ensures that the unmanaged resources are free when the code inside the using is finished. But I would like to catch the exceptions, such concurrency exceptions or others that can be happend.


I am thinking of two options. The first one, put the using inside the try block:



try
{
using(....)
{
//my code
}
}
catch
{
throw;
}

The second solution, put the try catch inside the the using:



using(...)
{
try
{
//my code
}
catch
{
throw;
}
}

My doubt is about disposing dbContext. For example, if I get an exception such as null reference in my code, becuase I try to access to a null variable. Will the dbContext dipose in both cases? or in some of the cases will not?


Are there others options to catch exceptions and ensure the disposing of the dbContext?


Thank so much.


No comments:

Post a Comment