all Python 3sqlite3exception
sqlite3.Error
exceptions
Base class of the other exceptions in the sqlite3 module (subclass of Exception); catch all database errors with a single except.
Syntax
raise sqlite3.Error
Catch sqlite3.Error at the edge of your program, where you decide what to tell the user; deeper down prefer the specific class, otherwise a typo in SQL (OperationalError) and a UNIQUE violation (IntegrityError) end up in the same handler. Since Python 3.11 an exception that comes from SQLite itself carries sqlite_errorcode and sqlite_errorname, so you can branch on the engine's own error code instead of parsing the message text. Catching the exception does not undo anything by itself: call con.rollback(), or use with con, which commits or rolls back the transaction but does not close the connection.
Examples
import sqlite3
print(issubclass(sqlite3.DatabaseError, sqlite3.Error)) # → True
try:
sqlite3.connect(':memory:').execute('SELECT * FROM nope')
except sqlite3.Error as e:
print(type(e).__name__) # → OperationalError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy