gpt4 book ai didi

c# - 使用 & try/catch 嵌套

转载 作者:可可西里 更新时间:2023-11-01 09:10:19 30 4
gpt4 key购买 nike

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

问题...using block 和 try/catch 之间是否有正确的嵌套顺序?

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

或者您是否应该将 try/catch 嵌套在 using 语句中,并且只围绕执行数据库访问的语句?

是...

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 { }

比...更不正确

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 { }
}

最佳答案

越晚越好:它将避免屏蔽最终抛出 dy dispose 的异常。看这个article.

关于c# - 使用 & try/catch 嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9613127/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com