title: Exit gracefully if file doesn't exist
body: <p>I have following script in Python 3.2.3:</p>
  
  <pre><code>try:
      file = open('file.txt', 'r')
  except IOError:
      print('There was an error opening the file!')
      sys.exit()
  
  #more code that is relevant only if the file exists
  </code></pre>
  
  <p>How do I exit gracefully, if the file doesn't exist (or there is simply an error opening it)?</p>
  
  <p>I can use <code>exit()</code>, but that opens a dialog panel asking if I want to kill the application.</p>
  
  <p>I can use <code>sys.exit()</code>, but that raises a SystemExit exception which doesn't looks great in output. I get</p>
  
  <pre><code>Traceback (most recent call last):   
  File "file", line 19, in &lt;module&gt;
      sys.exit() SystemExit
  </code></pre>
  
  <p>I can use <code>os.exit()</code>, but that kills the Python on C level, without any cleanups I might be performing.</p>
  
  <p>I can use a boolean variable and wrap all subsequent code in if... but that is ugly, and this is not the only check I am performing. So I would have like six nested ifs...</p>
  
  <p>I just want to print the 'There was an error...' and exit. I am working in IDLE.</p>