Client 2—Adding Error Checking

If you look back to line 7 of Listing 17.1, you'll notice that client1 calls pgdb.connect() to connect to a PostgreSQL server. If anything goes wrong during this function call, Python will print a stack trace and abort the program.

If you want to intercept a connection error, you must wrap the call to pgdb.connect() in a try/except block. The Python DB-API specification defines a hierarchy of exception types that a conforming implementation may throw. The most general exception type is StandardError. All other DB-API exceptions are derived (directly or indirectly) from StandardError.

Listing 17.2 shows client2.py. This client calls pgdb.connect() inside of a try/except block and catches any exceptions derived from ...

Get PostgreSQL, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.