I'm trying to improve my error handling, Particularly I would like to handle IntegrityError exceptions from pygresql.
I'm getting the error "NameError: name 'IntegrityError' is not defined" so I need to import something. Is this possible? What do I need to import?
It's definitely possible and almost always advisable to catch the specific exceptions that are thrown by modules you're using.
You're correct that you need to import that specific exception from the package you're using, as it's not part of the python built in exceptions.
Looking at the
pygresql
docs (around p.88), it seems that most exceptions are raised from thepgdb
module.Potentially;
Or it maybe the
pgdb
module is inside thepygresql
module so it might befrom pygresql.pgdb import IntegrityError
. The actual import path may vary, but the syntax will be as above.