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);
}
}
If you have try catch within the loop it gets executed completely inspite of exceptions.
Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.
One reason to avoid #1 is that it poisons your ability to use exception breakpoints. Normal-functioning code will never purposefully trigger a null pointer exception. Thus, it makes sense to set your debugger to stop every time one happens. In the case of #1, you'll probably get such exceptions routinely.
You should not catch any exceptions that you can't handle, because that will just obfuscate errors that may (or rather, will) bite you later on. Show activity on this post. I would recommend against this practice. Putting code into try-catch blocks when you know the types of exceptions that can be thrown is one thing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With