Monday, October 24, 2005

Python: retrieving the oracle error code

Anthony Tuininga gave me this hint on retrieving the Oracle error code from a cx_python program:
try:
    cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, e:
    print "Exception:", e    # this is what you are looking at right now
    errorObj, = e.args       # this is the actual "error" that cx_Oracle raises
    print "ErrorCode:", errorObj.code
    print "ErrorMessage:", errorObj.message
Causing Guido van Rossum to ask
This is overly subtle. Why not write
    errorObj = e.args[0]
and received the response
No particularly good reason -- it just happens to be a way of indicating that there should be one and only one entry in the list. An exception is raised if there is not whereas args[0] does not raise the exception. Its an open question which is the better code.