开发者

Exceptions as a control mechanism

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

In one开发者_如何学C of my apps i do not use File.Exist even tho i EXPECT files to exist a good deal of the time. I try to create a file without overwriting the older and if it fails i rename as Filename (Try Number).ext and loop until it opens.

Should i used File.Exist in this case ? or should i continue to try opening a file, loop until i do then write pattern?


In my opinion exceptions should generally be reserved for truely exceptional circumstances for several reasons:

  1. Exceptions have a high performance overhead (though that might not really a problem when e.g. dealing with files)
  2. Having an application throing and swallowing a high amount of exceptions can make debugging very hard
    • You might swallow the exception you are looking for somewhere
    • It can make it kind of hard for others to follow the programmflow, exspecially if the exceptions are catched higher in the call-hierarchie

Of course in your specific case it might make sense to rely on the exceptions since checking File.Exitsts() beforehand doesn't guarantee that the file exists when it is accessed, so you might have to include the exceptional case anyhow


This question is known as LBYL vs. EAFP: Look Before You Leap vs. It's Easier to Ask Forgiveness Than Permission. There are many disussions of this topic here in SO.


I'd leave the whole "exceptions for exceptional situation" thing aside for now and simply analyse your situation in order to persuade you that it is correct and you should only use exceptions for exceptional situations.

In your case you seemingly do

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

You'd end up eating all CPU time very easy. If you do

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

You would be playing nice, giving your unused time to other processes and keep the CPU to a minimum

So in my opinion, I'd say that it would be a very good idea to test first.


I would recomend checking File.Exist, the exception path can be very performance costly otherwise.


Exceptions are for exceptional situations.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜