使用&try/catch嵌套

Jar*_*red 10 c# using-statement try-catch

这个问题更多的是做某事的正确方法......

问题是......在一个using块和一个块之间是否存在正确的嵌套顺序try/catch

是否可以将整个using语句嵌套在a中try/catch并保持using块的好处?(或者异常会导致using语句的结束部分被抛出窗口)

或者,您是否应该try/catchusing语句内部嵌套,并且只包含进行数据库访问的语句?

是...

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 { }
Run Code Online (Sandbox Code Playgroud)

少于/多于......

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 { }
}
Run Code Online (Sandbox Code Playgroud)

J.N*_*.N. 5

后者更好:它将避免掩盖异常最终抛出dy dispose.看到这篇文章.