ernest
ernest

Reputation: 1724

Can I gather a list of directories and iterate over them without stopping when an error occurs?

If I loop through a list of directories, I have to put the try{}catch{} block outside of the loop. If I put it inside of the loop, an error can occur on that directory before I even get a chance to catch it. Putting the try catch inside of the loop is the ideal scenario though, because it would allow me to catch the error and continue on to the next directory.

But since I'm forced to put the try catch on the outside, it will error on a directory and won't continue on to the next directory.

try
{
    foreach (string subDir in Directory.GetDirectories(path))
    {
        queue.Enqueue(subDir);
    }
}
catch (Exception ex)
{
   Console.Error.WriteLine(ex);
}

Any ideas on what I can do to get each directory, one at a time?

Upvotes: 0

Views: 89

Answers (3)

Michael Finger
Michael Finger

Reputation: 1120

Do you need to catch the specific error? If not, just fail fast. Directory.Exists will return false on both errors thrown and a non-existent path:

if(!Directory.Exists(path) {
    //error handling here
}

foreach (string subDir in Directory.GetDirectories(path))
{
    queue.Enqueue(subDir);
}

Correction: See MrBlue comments below regarding directory access.

Upvotes: 0

MrBlue
MrBlue

Reputation: 840

I assume the error you're getting is on the call to Directory.GetDirectories(path). If that's the case, do this in the try/catch before entering the loop.

string[] directories;

try
{
    directories = Directory.GetDirectories(path);
}
catch (Exception ex)
{
   Console.Error.WriteLine(ex);
}

foreach (string subDir in directories)
{
    queue.Enqueue(subDir);
}

Queue<T>.Enqueue doesn't throw any exceptions so you don't need a try/catch block for it.

Note that you'll need to either return; after an exception is thrown or check for directories being null, otherwise entering the foreach will throw a NullReferenceException.

Upvotes: 2

Racil Hilan
Racil Hilan

Reputation: 25351

Well, nothing prevents you from using two try/catch like this:

try
{
    foreach (string subDir in Directory.GetDirectories(path))
    {
        try
        {
            queue.Enqueue(subDir);
        }
        catch (Exception ex)
        {
            //Do whatever you want with the error.
        }
    }
}
catch (Exception ex)
{
   Console.Error.WriteLine(ex);
}

Upvotes: 0

Related Questions