异常作为控制机制
我正在阅读这篇文章并笑了 http://mcfunley.com/239 /exceptions-are-not-a-control-mechanism
在我的一个应用程序中,我不使用 File.Exist,即使我期望文件大部分时间都存在。我尝试创建一个文件而不覆盖旧文件,如果失败,我将重命名为 Filename (Try Number).ext 并循环直到它打开。
在这种情况下我应该使用 File.Exist 吗?或者我应该继续尝试打开一个文件,循环直到我写模式?
I was reading this post and laughed http://mcfunley.com/239/exceptions-are-not-a-control-mechanism
In one 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在我看来,出于以下几个原因,通常应该为真正的异常情况保留异常:
当然,在你的具体情况下,这可能是有意义的依赖异常,因为事先检查
File.Exitsts()
并不能保证文件在访问时存在,因此您可能必须包含异常情况In my opinion exceptions should generally be reserved for truely exceptional circumstances for several reasons:
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这个问题被称为 LBYL 与 EAFP:三思而后行与请求宽恕比请求许可更容易。 SO 中对此主题有许多讨论。
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.
我现在将整个“特殊情况的例外”放在一边,简单地分析您的情况,以说服您它是正确的,并且您应该只在特殊情况下使用例外。
在你的情况下,你似乎
会很容易地吃掉所有的CPU时间。如果你这样做,
你会表现得很好,将未使用的时间留给其他进程,并将 CPU 保持在最低限度。
所以在我看来,我会说首先进行测试是一个非常好的主意。
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
You'd end up eating all CPU time very easy. If you do
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.
我建议检查 File.Exist,否则异常路径可能会非常耗费性能。
I would recomend checking File.Exist, the exception path can be very performance costly otherwise.
例外是指特殊情况。
您所需要的只是一个测试;这没有什么特别的,所以使用 if File.Exist。
Exceptions are for exceptional situations.
All you need is a test; there is nothing exceptional about that, so use if File.Exist.