2011-07-05 97 views
3

gyus中引发的异常!假设我有这样简单的LINQ表达式如何处理在linq

IEnumerable<StopListMatchViewModel> 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() 
     } 

如果字符串不能按照指定的格式解析mask - 我得到FormatException。在调试器中,我可以在变量“res”的结果视图中了解它。实时我收到空集。

可能有很多不同的例外情况,可能会在执行LINQ期间发生。我怎么能抓住和处理它们?尝试catch块在这里不起作用,因为异常在我看来不会被提出。

回答

2

由于延迟执行,只有在您评估查询(例如通过使用.ToList()方法)之后才会执行查询。当时只会抛出异常。

为避免此问题,您需要修改查询。东西如下

IEnumerable<StopListMatchViewModel> 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() 
    } 

注:DateTime.MinValue时使用的rqResult.Row["MatchDate"]值是用来避免空

+1

TryParseExact是更好的办法来避免该异常 – VMAtm

0

使用TryParseExact方法,以避免不需要的异常空。
我不明白你为什么不能使用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;