[英]handling exceptions with linq queries
如何處理linq查詢中的異常? 例如,如果我有以下查詢:
var query = (from d in GetLHDb().daily_average
where d.findnsave_site_id == fnsID
&& d.test_path_id == pathId
&& d.date > nTimesDays
&& d.date <= yesterday
select new
{
loadtime = d.loadtime,
created_at = d.date
}).ToArray();
例如,如何處理查詢中的null異常? 我在網上搜索過,但其中很多都是VB。
try
{
var query = (from d in GetLHDb().daily_average
where d.findnsave_site_id == fnsID && d.test_path_id == pathId && d.date > nTimesDays && d.date <= yesterday
select new { loadtime = d.loadtime, created_at = d.date }).ToArray();
}
catch (NullReferenceException e)
{
ReportError();
}
就您而言,就像您在代碼中的任何其他位置一樣。 將您的.ToArray()
包裝在try/catch
塊中。 盡管在您的情況下,我將更加防御並正確處理null值。
try
{
var query = (from d in GetLHDb().daily_average
where d.findnsave_site_id == fnsID && d.test_path_id == pathId && d.date > nTimesDays && d.date <= yesterday
select new { loadtime = d.loadtime, created_at = d.date }).ToArray();
}
catch (Exception)
{
//do what you need to
}
在您的示例中,我看到三個可能的地方,您可能會獲得空引用異常,這是通過在GetLHDB為空時訪問GetLHDb().daily_average
,嘗試枚舉daily_average
為空或嘗試訪問其中的字段來實現的d
當它為null時( 我甚至不確定這是否可能發生 )。
我建議將GetLHDb()
的結果存儲到本地變量(例如lhdb
),然后lhdb
進行空檢查。 如果不為null,請執行lhdb.daily_average
檢查lhdb.daily_average
。 如果不是null,請繼續查詢。
更新:此外,如果d
為null,則可以使用d != null
來啟動where子句。
var lhdb = GetLHDb();
if(lhdb != null && lhdb.daily_average != null)
{
var query = (from d in lhdb.daily_average
where d != null // If d can't be null, remove this
&& d.findnsave_site_id == fnsID
&& d.test_path_id == pathId
&& d.date > nTimesDays
&& d.date <= yesterday
select new
{
loadtime = d.loadtime,
created_at = d.date
}).ToArray();
// Process the results
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.