Guarding against exceptions (preventative maintenance) when working with network / file system calls?

雨燕双飞 提交于 2019-12-06 02:11:32

I would have both if (file.Exists) and a try catch. Relying only on exception handling does not express explicitly what you have in mind. if (file.Exists) is self-explaining.

If someone deletes the file just in that millisecond between checking and working with the file, you can still get an exception. Nevertheless, there are also other conditions, which can lead to an exception: The file is read-only; you do not have the requested security permissions, and more.

I agree with your friend here for the most part (context depending on whether or not you have withheld pertinent information from your question). This is an example of an exception that can occur outside of your magnificent code. Checking for the existence of the file and performing your operation is a race condition.

The fact is that this exception can occur and there is NOTHING you can do to prevent it. You must catch it. It's completely out of your control. For example, what if the network goes down, lightning strikes your datacenter and it catches on fire, or a squirrel chews thru the cables? While it's not practical to try and figure out every single way in which the code will raise an exception, it is a good practice to do your best in situations where you know it's a good possibility and do your best to handle it.

I would say this depends on the context. if the file was just created and then this process ran, then it doesn't make sense to check if it exists. you can assume that it does because the code is still executing.

however if this is a file that is continuously deleted & created, then yes it does make sense to ensure it exists before continuing.

another factor is who/what is accessing the file. if there are multiple clients accessing the file then there is a greater chance of the file being modified/removed and therefore it would make sense to check if the file exists.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!