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

Question
-
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.
Wednesday, December 31, 2014 7:49 PM
Answers
-
You have to use the 1st method. A using block when an exception occurs jumps out of the using block so any code after the exception doesn't get executed.
jdweng
- Marked as answer by ComptonAlvaro Thursday, January 1, 2015 8:33 AM
Thursday, January 1, 2015 1:22 AM
All replies
-
You have to use the 1st method. A using block when an exception occurs jumps out of the using block so any code after the exception doesn't get executed.
jdweng
- Marked as answer by ComptonAlvaro Thursday, January 1, 2015 8:33 AM
Thursday, January 1, 2015 1:22 AM -
This thread might be helpful for you.
http://stackoverflow.com/questions/4590490/try-catch-using-right-syntax
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.- Proposed as answer by ryguy72 Saturday, January 10, 2015 3:04 PM
Thursday, January 1, 2015 9:02 AM -
[...]
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?
I think that the dbContext will be disposed in both of the cases, according to the purpose of using.
However, when you use the try–using variant, if an exception occurs inside the using, such as your concurrency issue, and then another one occurs inside the auto-disposing part provided by using, then the second exception will mask the first one. Consequently, the catch statements will not be able to react properly to concurrency exception, since the exception was suppressed. (That’s why throwing exception from Dispose is considered a contestable practice).
Therefore, consider the other variant too: using–try. In this case the inner try–catch will be able to catch the concurrency exception.
Thursday, January 1, 2015 10:47 AM