title: Correct way of handling exceptions in Python?
body: <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
  
  <p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
  I want to know how you generally deal with dependent, error prone statements.</p>
  
  <p>My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
  Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.</p>
  
  <p>For your consideration, an example:</p>
  
  <pre><code>try:
      server = smtplib.SMTP(host) #can throw an exception
  except smtplib.socket.gaierror:
      #actually it can throw a lot more, this is just an example
      pass
  else: #only if no exception was thrown we may continue
      try:
          server.login(username, password)
      except SMTPAuthenticationError:
          pass # do some stuff here
      finally:
          #we can only run this when the first try...except was successful
          #else this throws an exception itself!
          server.quit() 
      else:
          try:
              # this is already the 3rd nested try...except
              # for such a simple procedure! horrible
              server.sendmail(addr, [to], msg.as_string())
              return True
          except Exception:
              return False
          finally:
              server.quit()
  
  return False
  </code></pre>
  
  <p>This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?</p>
  
  <p>I am also interested in proper resource cleanup, even Python can manage that for itself. </p>
  
  <p>Thanks, Tom</p>