Reputation: 307
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
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
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