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

前端 未结 15 1547
挽巷
挽巷 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

    Exceptional handling should only be done or used in exceptional cases.

    In a scenario which depends on whether a File exists or not it doesn't make sense to use try catch block when simply you can do

    if(File.Exists(path))
    {
    }
    else
    {
    
    }
    

    Exceptional handling cause a lot of performance hit so try to minimize the exceptional cases by applying more check in your code like if File.Exists(path))

提交回复
热议问题