This question is more of a what is the RIGHT way to do something...
The question...is there a proper nesting order between a using
block and a try/catch
?
Is it ok to nest the entire using
statement inside of a try/catch
and maintain the benefits of a using
block? (or will an exception cause the closing portion of the using statement to get thrown out the window)
Or should you nest the try/catch
inside the using
statements and only surround the statements that do database access?
Is...
try {
using( tsmtcowebEntities db = new tsmtcowebEntities() ) {
violationList = ( from a in db.DriverTrafficViolationDetails
where a.DriverTrafficViolation.DriverApplicationId == DriverAppId
orderby a.DateOfOccurance descending
select a ).ToList<DriverTrafficViolationDetail>();
GeneralViolation = ( from a in db.DriverTrafficViolations
where a.DriverApplicationId == DriverAppId
select a ).FirstOrDefault();
}
} catch { }
less/more correct than...
using( tsmtcowebEntities db = new tsmtcowebEntities() ) {
try {
violationList = ( from a in db.DriverTrafficViolationDetails
where a.DriverTrafficViolation.DriverApplicationId == DriverAppId
orderby a.DateOfOccurance descending
select a ).ToList<DriverTrafficViolationDetail>();
GeneralViolation = ( from a in db.DriverTrafficViolations
where a.DriverApplicationId == DriverAppId
select a ).FirstOrDefault();
} catch { }
}
The later is better: it will avoid masking exceptions eventually thrown dy dispose
. See this article.