static string SomeMethodThatMightThrow(string s)
    {
        if (s[4] == 'C')
            throw new InvalidOperationException();
        return @"C:\newFolder\" + s;

    }
    static void Main(string[] args)
    {
       string[] files = { "fileA.txt", "B.txC", "fileC.txt","fileD.txt" };

    var exceptionDemoQuery =
        from file in files
        let n = SomeMethodThatMightThrow(file)
        select n;
    try
    {
        foreach (var item in exceptionDemoQuery)
        {
            Console.WriteLine("Processing {0}", item);
        }
    }

    catch (InvalidOperationException e)
    {
        Console.WriteLine(e.Message);

    }

    Console.WriteLine("Press any key to exit");
    Console.ReadKey();

}


输出是

处理C:\ newFolder \ fileA.txt

由于对象的当前状态,操作无效。

但我需要输出为:

处理C:\ newFolder \ fileA.txt

由于对象的当前状态,操作无效。

由于对象的当前状态,操作无效。

处理C:\ newFolder \ fileD.txt

请帮忙.............

最佳答案

执行SomeMethodThatMightThrow中包裹在try/catch中的foreach

例:

var exceptionDemoQuery =
    from file in files
    select file;

foreach (var item in exceptionDemoQuery)
{
  try
  {
    Console.WriteLine("Processing {0}", item);
    var n = SomeMethodThatMightThrow(item);
  }
  catch (Exception ex)
  {
    Console.WriteLine(e.Message);
  }
}

关于c# - C#中发生异常后如何继续,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4665707/

10-17 02:19