码迷,mamicode.com
首页 > 其他好文 > 详细

linq 在查询表达式中处理异常

时间:2017-11-03 11:27:07      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:clean   return   color   throws   operation   expect   stat   pts   有关详细信息   

在查询表达式的上下文中可以调用任何方法。 但是,我们建议避免在查询表达式中调用任何会产生副作用(如修改数据源内容或引发异常)的方法。 此示例演示在查询表达式中调用方法时如何避免引发异常,而不违反有关异常处理的常规 .NET Framework 指南。 这些指南阐明,当你理解在给定上下文中为何会引发异常时,捕获到该特定异常是可以接受的。 有关详细信息,请参阅异常的最佳做法

最后的示例演示了在执行查询期间必须引发异常时,该如何处理这种情况。

示例

在某些情况下,针对由查询内部引发的异常的最佳措施可能是立即停止执行查询。 下面的示例演示如何处理可能在查询正文内部引发的异常。 假定 SomeMethodThatMightThrow 可能导致要求停止执行查询的异常。

请注意,try 块封装 foreach 循环,且不对自身进行查询。 这是由于 foreach 循环正是实际执行查询时的点。 有关详细信息,请参阅 LINQ 查询简介

class QueryThatThrows
{
    static void Main()
    {
        // Data source.
        string[] files = { "fileA.txt", "fileB.txt", "fileC.txt" };

        // Demonstration query that throws.
        var exceptionDemoQuery =
            from file in files
            let n = SomeMethodThatMightThrow(file)
            select n;

        // Runtime exceptions are thrown when query is executed.
        // Therefore they must be handled in the foreach loop.
        try
        {
            foreach (var item in exceptionDemoQuery)
            {
                Console.WriteLine($"Processing {item}");
            }
        }

        // Catch whatever exception you expect to raise
        // and/or do any necessary cleanup in a finally block
        catch (InvalidOperationException e)
        {
            Console.WriteLine(e.Message);
        }

        //Keep the console window open in debug mode
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // Not very useful as a general purpose method.
    static string SomeMethodThatMightThrow(string s)
    {
        if (s[4] == C)
            throw new InvalidOperationException();
        return @"C:\newFolder\" + s;
    }
}
/* Output:
    Processing C:\newFolder\fileA.txt
    Processing C:\newFolder\fileB.txt
    Operation is not valid due to the current state of the object.
 */

 

linq 在查询表达式中处理异常

标签:clean   return   color   throws   operation   expect   stat   pts   有关详细信息   

原文地址:http://www.cnblogs.com/dehuachenyunfei/p/7776854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!