title: Python Error-Checking Standard Practice
body: <p>I have a question regarding error checking in Python. Let's say I have a function that takes a file path as an input:</p>
  
  <pre><code>def myFunction(filepath):
      infile = open(filepath)
      #etc etc...
  </code></pre>
  
  <p>One possible precondition would be that the file should exist. </p>
  
  <p>There are a few possible ways to check for this precondition, and I'm just wondering what's the best way to do it.</p>
  
  <p>i) Check with an if-statement:</p>
  
  <pre><code>if not os.path.exists(filepath):
      raise IOException('File does not exist: %s' % filepath)
  </code></pre>
  
  <p>This is the way that I would usually do it, though the same IOException would be raised by Python if the file does not exist, even if I don't raise it.</p>
  
  <p>ii) Use assert to check for the precondition:</p>
  
  <pre><code>assert os.path.exists(filepath), 'File does not exist: %s' % filepath
  </code></pre>
  
  <p>Using asserts seems to be the "standard" way of checking for pre/postconditions, so I am tempted to use these. However, it is possible that these asserts are turned off when the -o flag is used during execution, which means that this check might potentially be turned off and that seems risky.</p>
  
  <p>iii) Don't handle the precondition at all</p>
  
  <p>This is because if filepath does not exist, there will be an exception generated anyway and the exception message is detailed enough for user to know that the file does not exist</p>
  
  <hr>
  
  <p>I'm just wondering which of the above is the standard practice that I should use for my codes.</p>