Exceptions as a control mechanism

I read this post and laughed http://mcfunley.com/239/exceptions-are-not-a-control-mechanism

In one of my applications, I do not use File.Exist even in EXPECT files to exist for a long time. I try to create a file without overwriting the older one, and if that fails, I will rename the file name (Try Number) .ext and loop until it opens.

Should I use File.Exist in this case? or should I continue to try to open the file loop until I write a template?

0
source share
5 answers

In my opinion, exceptions, as a rule, should be reserved for truly exceptional circumstances for several reasons:

  • Exceptions have high performance (although this may not be a problem, for example, when working with files).
  • When submitting an application and swallowing a large number of exceptions it can be very difficult to debug
    • You can catch the exception you are looking for somewhere
    • This can make it difficult for others to keep track of the program flow, especially if exceptions are exceeded in the call hierarchy.

Of course, in your particular case it may be wise to rely on exceptions, since checking File.Exitsts()in advance does not guarantee that the file exists when it is accessed, so you may need to include an exceptional case anyway

+2

LBYL EAFP: ", ", " , ". , SO.

+1

, , .

, ,

while (!opened) { 
   try {
       <file_open>;
       opened = true
   } catch (exception) {
       //ignore
   }
}

.

while (!opened) { 
   if (file.exists) {
       <file_open>
       opened = true
   } else {
       Thread.sleep(<some_time>);
   }
}

, CPU

, , , .

+1

File.Exist, .

0
source

Exceptions for exceptional situations.

All you need is a test; this is nothing exceptional, so use if File.Exist.

0
source

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


All Articles