Handling database errors in code
Catches a failed database call, such as an IntegrityError from a broken constraint, so the program shows a friendly message instead of crashing. Call rollback() to undo.
Understanding Handling database errors in code in QCE Digital Solutions Unit 2
What it does: The risky execute() call sits in try, and the except sqlite3.Error block runs only if the database call fails, showing a friendly message. conn.rollback() cancels changes made since the last commit, so a failed change does not leave the data partly saved. IntegrityError is raised when a constraint such as PRIMARY KEY, UNIQUE, NOT NULL or FOREIGN KEY is broken. sqlite3 has no ConnectionError class. The exception class is named without brackets. Adding () is incorrect syntax in this form and a common slip.
Common mistakes: A try block must end with a colon. Without it Python raises a SyntaxError before the error handling can work. It should be try:. The cursor method is execute, not execut. The typo raises an AttributeError, which the sqlite3.Error handler would not catch. It should be cur.execute(sql, vals).
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 337–409) and word search (Modules 234–409).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
except sqlite3.Error:Fill in the Blanks
Spot the Error
Student with a class code? Join your class →