C.W.K.
Stream
Lesson 09 of 10 · published

Error Handling — sqlite3 Exception Classes

~10 min · python, errors, exceptions

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Catch the right thing, not the world

The sqlite3 module raises a small hierarchy of exceptions. Knowing them lets you handle expected failures (constraint violations, locked databases) without catching everything.

  • sqlite3.Error — base class for everything.
  • sqlite3.DatabaseError — anything from inside the engine.
  • sqlite3.IntegrityError — constraint violations (UNIQUE, NOT NULL, FK, CHECK).
  • sqlite3.OperationalError — operational issues (locked, malformed, disk full).
  • sqlite3.ProgrammingError — usage errors (closed cursor, wrong number of params).
  • sqlite3.InterfaceError — driver-side problems before SQLite saw the call.
Tip: except sqlite3.IntegrityError is how you idiomatically handle 'duplicate key' for an INSERT that may collide. Combined with UPSERT (track 4), most apps end up with very few catch sites.

Code

Catching the right exception·python
import sqlite3

try:
    conn.execute('INSERT INTO users(email) VALUES (?)', ('dup@x.com',))
except sqlite3.IntegrityError as e:
    print('duplicate or other constraint failure:', e)
except sqlite3.OperationalError as e:
    print('operational issue (locked, disk, etc.):', e)
except sqlite3.DatabaseError as e:
    print('something else from the engine:', e)

External links

Exercise

Trigger each exception class on purpose: an IntegrityError (UNIQUE violation), an OperationalError (open a non-existent table), a ProgrammingError (use a closed cursor). For each, write a tight except that handles the specific case without swallowing the others. Then think about which of these belong in user-facing error messages and which belong in logs only.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.