Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
         }

    }
like image 747
Emma Geller-Green Avatar asked Jan 08 '16 18:01

Emma Geller-Green


People also ask

Can you have a try catch in a for loop?

If you have try catch within the loop it gets executed completely inspite of exceptions.

Is it bad practice to use try catch?

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.

Why you should avoid try catch?

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.

Should I put everything in a try catch?

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.


1 Answers

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.

like image 83
mac Avatar answered Oct 22 '22 19:10

mac