【问题标题】:How to handle exception raised in linq如何处理 linq 中引发的异常
【发布时间】:2011-07-05 06:52:51
【问题描述】:

你!假设我有这么简单的 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()
        }

如果无法根据指定的格式掩码解析字符串 - 我得到 FormatException。在调试器中,我可以在变量“res”的结果视图中了解它。实时我得到空集合。

在执行 LINQ 期间可能会发生许多不同异常的示例。我怎么能抓住和处理它们? try catch 块在这里不起作用,因为在我看来异常不会被引发。

【问题讨论】:

    标签: c# linq exception-handling


    【解决方案1】:

    由于延迟执行,在您评估查询之前不会执行查询,例如通过使用.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.MinValuerqResult.Row["MatchDate"]的值为null时使用,用于避免null

    【讨论】:

    • TryParseExact 是避免异常的更好方法
    【解决方案2】:

    使用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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2010-09-17
      • 1970-01-01
      相关资源
      最近更新 更多