如何处理linq中引发的异常

本文关键字:异常 linq 何处理 处理 | 更新日期: 2023-09-27 18:01:01

gyus!假设我有这样一个简单的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块在这里不起作用,因为在我看来异常并没有被提出。

如何处理linq中引发的异常

由于延迟执行,所以在评估查询之前(例如使用.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()
    }

注意:当rqResult.Row["MatchDate"]的值为空时使用DateTime.MinValue,用于避免为空

使用TryParseExact方法来避免不需要的异常
我不明白你为什么不能用试跳挡?你真的认为它没有被养大吗?此外,您还应该检查数据库中的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;