Emma Geller-Green
Emma Geller-Green

Reputation: 307

Is it bad Practice to Put a Try-Catch in a For Loop?

I'm creating a command-line utility that will delete sub-directories/files. If a file is in use, the System.IO.IOException is thrown. I use a try-catch block within my for loop.

Question:

1.Is it bad practice to have a try-catch within a for loop?

2.If Yes, what is a better alternative?

My Code:

  System.IO.DirectoryInfo di = new DirectoryInfo(path);

    foreach (FileInfo file in di.GetFiles())
    {
         try
         {
             file.Delete(); 
         }
         catch(System.IO.IOException)
         {
           Console.WriteLine("Please Close the following File {0}", file.Name);
         }

    }

Upvotes: 7

Views: 2949

Answers (2)

Kundan Kumar
Kundan Kumar

Reputation: 1

No its not a bad practice to skip the exception deliberately. But looking at your use case

I'm creating a command-line utility that will delete sub-directories/files. If a file is in use, the System.IO.IOException is thrown.

I would suggest you to delete the directory rather than looping on each file in the subfolder. https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.delete?view=net-5.0

Upvotes: 0

mac
mac

Reputation: 504

No this can be quite useful. For example: If you didn't want to completely stop the loop if an Exception was thrown, or if there was extra code that shouldn't be ran for the current iteration due to the Exception you could do something like the following.

System.IO.DirectoryInfo di = new DirectoryInfo(path);

foreach (FileInfo file in di.GetFiles())
{
     try
     {
         file.Delete(); 
     }
     catch(System.IO.IOException)
     {
       Console.WriteLine("Please Close the following File {0}", file.Name);
       continue;
     }
     //
     // Other Code 
     //
}

This way you can log the error to review later but still process the rest of what you were trying to process.

Upvotes: 15

Related Questions