Is it a bad practice to put a try-catch in a loop?

I am creating a command line utility that will delete subdirectories / files. If the file is used, a System.IO.IOException . I am using a try-catch block inside a for loop.

Question:

1. Is there a bad practice to have an attempt in a for loop?

2. If what is the best alternative?

My code is:

  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); } } 
+5
source share
1 answer

No, it can be very helpful. For example: If you did not want to completely stop the loop, if an exception was thrown, or if additional code was added that should not be run for the current iteration due to the exception, you can 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 // } 

That way, you can log the error so you can review it later, but still handle the rest of what you tried to handle.

+14
source

Source: https://habr.com/ru/post/1240184/


All Articles