How to decide between using if/else vs try/catch?

前端 未结 15 1552
挽巷
挽巷 2020-12-05 06:44

When writing code, how does one decide between using if/else or try/catch? For example, in checking for a file, should this be based on if/else (if (File.Exists)) or a try/c

15条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 07:28

    in general it depends

    For file based stuff you almost always want to try the operation and handle failures rather than check first. the reason being that the file system is a shared resource and you cannot guarantee that after file.exists returns true the file does exist as some other process may have deleted it in the mean time.

提交回复
热议问题