Exception Handling

All exceptions raised by cx_Oracle are inherited from cx_Oracle.Error. See Exceptions for more details on the various exceptions defined by cx_Oracle. See the exception handling section in the API manual for more details on the information available when an exception is raised.

Applications can catch exceptions as needed. For example, when trying to add a customer that already exists in the database, the following could could be used to catch the exception:

try:
    cursor.execute("insert into customer values (101, 'Customer A')")
except cx_Oracle.IntegrityError:
    print("Customer ID already exists")
else:
    print("Customer added")

If information about the exception needs to be processed instead, the following code can be used:

try:
    cursor.execute("insert into customer values (101, 'Customer A')")
except cx_Oracle.IntegrityError as e:
    errorObj, = e.args
    print("Customer ID already exists")
    print("Error Code:", errorObj.code)
    print("Error Message:", errorObj.message)
else:
    print("Customer added")