如何处理linq中引发的exception
gyus! 假设我有这么简单的LINQ表达式
IEnumerable res = from rqResult in MatchesList select new StopListMatchViewModel ( ) { MatchDate = DateTime.ParseExact(rqResult.Row["MatchDate"].ToString(), "dd.MM.yyyy HH:m:ss", fmtInfo), Remark = rqResult.Row["Remark"].ToString() }
如果无法根据指定的格式掩码解析字符串 – 我得到FormatException。 在调试器中,我可以在变量“res”的结果视图中了解它。 实时我得到空集合。
在执行LINQ期间可能会发生许多不同exception的例子。 我怎么能抓住并处理它们? 尝试catch块在这里不起作用,因为exception在我看来不会被提出。
由于延迟执行,在您评估查询之前不会执行查询,例如通过使用.ToList()
方法。 只会在那个时候抛出exception。
要避免此问题,您需要修改查询。 如下的东西
IEnumerable res = from rqResult in MatchesList select new StopListMatchViewModel { MatchDate = DateTime.ParseExact( ((rqResult.Row["MatchDate"]==null) ? rqResult.Row["MatchDate"] : DateTime.MinValue).ToString(), "dd.MM.yyyy HH:m:ss", fmtInfo), Remark = rqResult.Row["Remark"].ToString() }
注意:当rqResult.Row["MatchDate"]
值为null时,使用DateTime.MinValue
,用于避免null
使用TryParseExact方法可以避免不需要的exception。
我不明白为什么你不能使用try-catch块? 你真的认为它没有被提升吗? 您还应检查数据库中的NULL值:
MatchDate = Convert.IsDBNull (rqResult.Row["MatchDate"]) ? DateTime.MinValue : DateTime.ParseExact(rqResult.Row["MatchDate"].ToString(), "dd.MM.yyyy HH:m:ss", fmtInfo), Remark = (string)rqResult.Row["Remark"] ?? String.EmptyString;