5

I have this piece of code:

try { var files = from folder in paths from file in Directory.EnumerateFiles(path, pattern, searchOption) select new Foo() { folder = folder, fileName = file }; Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, currentFile => { DoWork(currentFile); }); } catch (Exception ex) { } 

When I have an exception in Directory.EnumerateFiles, I can't catch this exception in this piece of code. The exception is caught by the method that calls this snippet.

From Visual Studio, in debug mode, the exception is caught by Visual Studio (for example a DirectoryNotFoundException).

5
  • 5
    You have to add the try/catch within the foreach. See this MSDN article Commented Dec 19, 2014 at 16:53
  • You could also call EnumerateFiles before the LINQ expression and wrap that call in a try/catch. Commented Dec 19, 2014 at 16:55
  • Suppose in the parallel loop one file throws an exception and another one throws its own. How could you deal with two "parallel" exceptions in a single try-catch block? Commented Dec 19, 2014 at 16:55
  • 1
    you could call files.ToList() before the Parallel and then your catch would fire. Commented Dec 19, 2014 at 17:00
  • Just wondering if you should be passing folder to Directory.EnumerateFiles instead of path? Commented Dec 19, 2014 at 17:00

3 Answers 3

12

The problem is that you are invoking the code asynchronously here:

Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, currentFile => { DoWork(currentFile); }); 

This makes the calls on separate threads and not on your main thread.

Use a try & catch block like this:

Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, currentFile => { try { DoWork(currentFile); } catch (Exception ex) { ... } }); 
Sign up to request clarification or add additional context in comments.

Comments

-1

The best way to catch any exceptions that may be thrown while in the loop is to use System.AggregateException. This is because any exception thrown in any one thread in the loop might cause other threads to throw exceptions too.

Comments

-1

If you want to catch the Directory not found exception you may add the two lines

catch (DirectoryNotFoundException dnfe) { throw dnfe; } 

1 Comment

Whilst it is definitely better to catch the specific exception you're interested in, in this instance the OP isn't able to catch any exceptions where they want to - adding this to the code will not help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.