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

前端 未结 15 1506
挽巷
挽巷 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条回答
  •  萌比男神i
    2020-12-05 07:24

    As it is obvious from all the answers, there is no standard/approved way to decide whether you should use one or the other. If done correctly, both methods will be effective. If done incorrectly, both methods will be inefficient.

    I prefer if/else statements when it is meaningful(i.e. inside my own functions) and Try blocks when I call functions I have no control over.

    In the above example, File.Exists() would be sufficient if you control the file(meaning no other program is likely to manipulate it) but not sufficient if there is a possibility that the file will be gone between checking and using.

    File operations, in general, are better handled with exceptions in most cases, in my experience, because these very file operations, in c#, are raising exceptions. They do not return error codes that could be checked with if statements.

提交回复
热议问题