如何处理在linq中引发的异常 [英] How to handle exception raised in linq

查看:114
本文介绍了如何处理在linq中引发的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gyus!假设我有这样简单的LINQ表达式

gyus! Suppose I have such simple LINQ expression

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的结果视图中了解它。实时我收集空。

if string couldn't be parsed according to specified format mask - I get FormatException. In debugger I can know about it in results view of variable "res". In realtime i get empty collection.

在执行期间可能会出现许多不同例外的例子LINQ。我如何抓住并处理它们?尝试catch块不工作在这里,因为异常似乎在我不被提出。

There could be many examples of different exceptions that could happen during executiong LINQ. How could I catch and handle them? try catch block doesn't work here, because exception seems to me to not to be raised.

推荐答案

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

Because of deferred execution the query is not executed until you evaluate the query, such as by making use of the .ToList() method. The exception will be thrown at that time only.

为避免出现此问题,您需要修改查询。一些如下

To avoid the problem you need to modify the query. something as below

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当$ rqResult.Row [MatchDate] 的值为null,用于避免null

Note : DateTime.MinValue is used when the value of rqResult.Row["MatchDate"] is null which used to avoid null

这篇关于如何处理在linq中引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆