Skip to main content

How to Catch SQLite Errors in Python with sqlite3.Error

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

Database code fails in more than one way: a table that isn't there, a value that breaks a rule, a file that can't be opened. Every one of those errors from the sqlite3 module is a kind of sqlite3.Error, so one except can catch them all, and the exception still tells you which it was. This guide triggers two different errors and catches both, with real output from Python 3.15.2.

Syntax​

Syntax
try:
connection.execute("<SQL statement>")
except sqlite3.Error as error:
<handle error>
PartWhat it means
except sqlite3.ErrorCatches any error the sqlite3 module raises
type(error).__name__The exact kind, such as OperationalError or IntegrityError
error.sqlite_errornameSQLite's own name for the error, such as SQLITE_CONSTRAINT_UNIQUE

Python's sqlite3 documentation: "The base class of the other exceptions in this module. Use this to catch all errors with one single except statement." Errors that come from the SQLite library also carry sqlite_errorname, "The symbolic name of the numeric error code from the SQLite API", added in Python 3.11.

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

The table's title column is UNIQUE, so the same title can't go in twice:

catch_sqlite_error.py
import sqlite3

connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE books (title TEXT UNIQUE)")
connection.execute("INSERT INTO books VALUES ('Rivers of Salt')")

for sql in ["SELECT * FROM authors", "INSERT INTO books VALUES ('Rivers of Salt')"]:
try:
connection.execute(sql)
except sqlite3.Error as error:
print(f"{type(error).__name__} ({error.sqlite_errorname}): {error}")

connection.close()

The catch_sqlite_error.py script in a macOS-style code window: a books table with a unique title, then a loop runs a SELECT from a missing authors table and a duplicate INSERT, catching sqlite3.Error and printing the error's class, sqlite_errorname and message.

  • The first statement reads from authors, a table that doesn't exist.
  • The second inserts a title that's already there.
  • One except sqlite3.Error handles both, and the print shows the class, SQLite's error name and the message.

Step 2: Run It​

Terminal
uv run python catch_sqlite_error.py
Output
OperationalError (SQLITE_ERROR): no such table: authors
IntegrityError (SQLITE_CONSTRAINT_UNIQUE): UNIQUE constraint failed: books.title

The output in a terminal: OperationalError with SQLITE_ERROR, no such table: authors, then IntegrityError with SQLITE_CONSTRAINT_UNIQUE, UNIQUE constraint failed: books.title.

Two different problems, one except. The missing table raised an OperationalError, and the duplicate title an IntegrityError, with the exact rule it broke, SQLITE_CONSTRAINT_UNIQUE. Both are subclasses of sqlite3.Error, so the loop carried on after each.

Common Mistakes​

MistakeWhat happensDo this instead
except sqlite3.OperationalError around an insert that breaks a UNIQUE ruleNot caught: it's an IntegrityError, so the script stops with sqlite3.IntegrityError: UNIQUE constraint failed: ...Catch sqlite3.IntegrityError, or sqlite3.Error for all of them
Catching ExceptionA typo is caught too and looks like a database error: AttributeError: 'sqlite3.Connection' object has no attribute 'exceute'Catch sqlite3.Error

Troubleshooting​

SymptomLikely causeFix
OperationalError: no such tableThe table isn't in this database: a different file, or a new empty oneCheck the path given to connect()
IntegrityError: UNIQUE constraint failedThe value is already in a UNIQUE columnCheck first, or handle the error

FAQ​

How do I tell a duplicate apart from other errors?​

Catch sqlite3.IntegrityError before sqlite3.Error, or check error.sqlite_errorname == "SQLITE_CONSTRAINT_UNIQUE".

Is sqlite3.Error a subclass of Exception?​

Yes. The documentation: "Error is a subclass of Exception."

Conclusion​

One except sqlite3.Error caught a missing table and a duplicate title, and type(error).__name__ and sqlite_errorname named each one exactly.

Additional Resources​