When is it okay to check if a file exists?

前端 未结 18 2312
再見小時候
再見小時候 2020-11-28 06:52

File systems are volatile. This means that you can\'t trust the result of one operation to still be valid for the next one, even if it\'s the next line of code. You can\'t

18条回答
  •  执念已碎
    2020-11-28 07:23

    I'd only check it if I expect it to be missing (e.g. the application settings) and only if I have to read the file.

    If I have to write to the file, it's either a logfile (so I can just append to it or create a new one) or I replace the contents of it, so I might as well recreate it anyway.

    If I expect that the file exists, it would be right that an Exception is thrown. Exception handling should then inform the user or perform recovery. My opinion is that this results in cleaner code.

    File protection (i.e. not overwriting (possibly important) files) is different, in that case I'd always check whether a file exists, if the framework doesn't do that for me (think SaveFileDialog)

提交回复
热议问题