Can exceptions be written for specific errors? Like database "XXX" does not exist

StackOverflow https://stackoverflow.com/questions/22289673

  •  12-06-2023
  •  | 
  •  

I would like to write and exception for the database does not exist, so I can create it and return back to the top (retry the connection).

How do you get specific when writing exceptions?

Can you have two or more exceptions?

try:
    db_con = psycopg2.connect(host='HOSTNAME', database='MYDB', user='USERNAME', password='PASSWORD')
    cur = db_con.cursor()
    cur.execute('SELECT version()')
    ver = cur.fetchone()
    print ver

except psycopg2.DatabaseError, e:
    print 'Error %s' % e
    sys.exit(1)

finally:
    if db_con:
        db_con.close()
有帮助吗?

解决方案

You should read the python documentation on Exceptions.

But generally speaking yes, you can define your own exception types just like any other class by extending Exception or any other appropriate error type (in this case I'd probably use IOError)

Example:

class NoDatabaseError(IOError):
      pass

And then in the code above the database open:

 try:
    open_database(database)
 except NoDatabaseError as e:
    print('Could Not Open The Database: '+str(e))
 except Exception as e:
    print('Something Unexpected Went On:'+str(e))

If that's not what you're asking, you should clarify your question.

其他提示

Creating your own Exception is just a matter of inheritance:

class DatabaseDoesNotExist(IOError):
    pass

raise DatabaseDoesNotExist()

You can also raise nested exceptions by listing one as cause for the other:

except psycopg2.DatabaseError as e:
    raise DatabaseDoesNotExist('message', e)     # python 2
    raise DatabaseDoesNotExist('message') from e # python 3

This will preserve the traceback prior to your intervention.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top