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

前端 未结 15 1514
挽巷
挽巷 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:05

    You use try/catch when something unexpected ( an exception ) might happen and you want to do something special about it, like :

    try
    {
       //Do something that might rise an exception, say a division by 0
       //this is just an easy example as you might want to check if said value is not 0
       //before dividing
       int result = someNumberOfMine / anUnsafeNumber;
    }
    catch
    {
       //if something unexpected happened, do a special treament
    }
    

    In your particular case, I would recommand using File.Exists to verify the presence of the file instead of using a try/catch block since the presence or not of the file can be checked before doing anything with it.

提交回复
热议问题