23. Catching Exceptions — python-oracledb 3.2.0b1 documentation (original) (raw)

python-oracledb

All exceptions raised by python-oracledb are inherited fromoracledb.Error. See Oracledb Exceptions and Oracledb _Error Objects for information about attributes.

See Error Handling in Thin and Thick Modes for differences between the python-oracledb Thin andThick modes.

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

try: cursor.execute("insert into customer values (101, 'Customer A')") except oracledb.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 oracledb.IntegrityError as e: error_obj, = e.args print("Customer ID already exists") print("Error Code:", error_obj.code) print("Error Full Code:", error_obj.full_code) print("Error Message:", error_obj.message) else: print("Customer added")

This will print output like:

Customer ID already exists Error Code: 1 Error Full Code: ORA-00001 Error Message: ORA-00001: unique constraint (CJ.PK) violated

23.1. Error Handling in Thin and Thick Modes

The Thin and Thick modes of python-oracledb return some errors differently.

The python-oracledb Thin mode code generates error messages with the prefix “DPY”.

In python-oracledb Thick mode:

Errors generated by the Oracle Database itself commonly have the error prefix “ORA”.

Some differences between python-oracledb Thin and Thick mode errors are shown in the examples below: