這個問題更多的是什麼是正確的方式做一些事情......和try/catch語句嵌套
的問題...有沒有using
塊和try/catch
之間的適當嵌套順序?
套住try/catch
中的整個using
聲明並保持using
塊的優點是可以的嗎? (或者會導致使用語句的關閉部分被拋出窗口)
或者你應該在using
語句中嵌套try/catch
,並且只圍繞執行數據庫訪問的語句?
是...
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 { }
}
你真的需要在所提供的代碼的應用程序的所有細節?我認爲一個簡單的例子就足夠了。 – 2012-03-08 05:09:16
空的catch塊是一個非常糟糕的編程習慣。不要這樣做!你會後悔的。 – phoog 2012-03-08 05:34:06
@JonathonReinhart對於我來說,複製和粘貼一段代碼比構成一個例子更簡單。當我覺得把代碼放在這個世界可能會很糟糕時,我編寫代碼。在這種情況下,我看不到任何消極因素,爲什麼不呢? – Jared 2012-03-08 19:38:02