title: cx_Oracle and Exception Handling - Good practices?
body: <p>I'm trying to use cx_Oracle to connect to an Oracle instance and execute some DDL statements:</p>
  
  <pre><code>db = None
  try:
      db = cx_Oracle.connect('username', 'password', 'hostname:port/SERVICENAME')
  #print(db.version)
  except cx_Oracle.DatabaseError as e:
      error, = e.args
      if error.code == 1017:
          print('Please check your credentials.')
          # sys.exit()?
      else:
          print('Database connection error: %s'.format(e))
  cursor = db.cursor()
  try:
      cursor.execute(ddl_statements)
  except cx_Oracle.DatabaseError as e:
      error, = e.args
      if error.code == 955:
          print('Table already exists')
      if error.code == 1031:
          print("Insufficient privileges - are you sure you're using the owner account?")
      print(error.code)
      print(error.message)
      print(error.context)
  cursor.close()
  db.commit()
  db.close()
  </code></pre>
  
  <p>However, I'm not quite sure what's the best design for exception handling here.</p>
  
  <p>Firstly, I create the <code>db</code> object inside a try block, to catch any connection errors.</p>
  
  <p>However, if it can't connect, then <code>db</code> won't exist further down - which is why I set <code>db = None</code> above. However, is that good practice?</p>
  
  <p>Ideally, I need to catch errors with connecting, then errors with running the DDL statements, and so on.</p>
  
  <p>Is nesting exceptions a good idea? Or is there a better way of dealing with dependent/cascaded exceptions like this?</p>
  
  <p>Also, there are some parts (e.g. connection failures) where I'd like the script to just terminate - hence the commented out <code>sys.exit()</code> call. However, I've heard that using exception handling for flow control like this is bad practice. Thoughts?</p>