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

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

    0 讨论(0)
  • 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))

    0 讨论(0)
  • 2020-12-05 07:05

    For this you know the file exit problem. So you prefer if else.

    If you don't know the problem, better to use try catch.

    i suggest the both, like below

    try 
    {
      if(File.Exists(path)) 
      { 
         do work
      } 
      else 
      {
         messagebox.show("File Path Not Exit");
      } 
    }
    catch(Exception e) 
    {
     messagebox.show(e); 
    }
    

    it catch all the errors, which we not think.

    0 讨论(0)
  • 2020-12-05 07:06

    You should never use try/catch for flow control.

    Generating an exception is an extremely expensive action. If/else is much faster and cleaner.

    0 讨论(0)
  • 2020-12-05 07:09

    When the file is expected to not exist, check for existence first. But when the missing file is a unusual state you should indicate this exceptional state with an exception.

    So the basic idea is: Try to avoid exceptions on expectable circumstances.

    0 讨论(0)
  • 2020-12-05 07:10

    Generally you should do both. try/catch to avoid exceptional situations (file was suddenly deleted from another thread). And if/else to handle non-exceptional (check if file exists). Try/catch is relatively slower than a usual if/else so it does not worth to use it for everything.

    0 讨论(0)
提交回复
热议问题