1

I try to use the recursive built in method:

public IEnumerable<string> Foo(string path)
{
    try
    {
        foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
        {
            yield return file;
        }
    }
    catch (Exception)
    { }
}

And received this error:

Cannot yield a value in the body of a try block with a catch clause

How can I use the try-catch in order to avoid me method to crash is I don't have folder permission ?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user2214609
  • 4,713
  • 9
  • 34
  • 41
  • That piece of code doesn't make a lot of sense. What do you want to do if you catch an exception? After all, the exception block *is* the logic of the method, otherwise you could have just called Directory.EnumerateFiles in your program directly. – nvoigt May 26 '13 at 09:24
  • From [Compiler Error CS1626](http://msdn.microsoft.com/en-us/library/cs1x15az(v=vs.90).aspx) `A yield statement is not allowed in a try block if there is a catch clause associated with the try block. To avoid this error, move the yield statement out of the catch clause.` Of course this doesn't completely answer your question. – Soner Gönül May 26 '13 at 09:27
  • You mean just put Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories) inside foreach and inside Try ? – user2214609 May 26 '13 at 09:46
  • I'm with @nvoigt here. Explain why you're trying to do this strange thing. Why is there a foreach and a yield return there at all? You already have the collection in hand. Why not simply write `try { return Directory.EnumerateFiles(...); } catch { return Enumerable.Empty(); }` ? Is there an exception on a `MoveNext()` perhaps? – Eric Lippert May 26 '13 at 14:16

1 Answers1

1
public IEnumerable<string> Foo(string path)
{
    var files = new List<string>();
    try
    {
      files.AddRange(Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories));
    }
    catch (Exception)
    {
       // this is bad style. You should catch more specific exceptions
    }

    return files;
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • If you're doing it this (non-lazy) way, you might as well just use `Directory.GetFiles()` instead. – svick May 26 '13 at 09:35