← QCE Digital Solutions Unit 2

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).

Class: _____________________  ·  Name: _____________________  ·  Date: _________

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.

Learning
Duo
Which code stops a failed INSERT from crashing the program with a long error message?
try: cur.execute(sql) except sqlite3.Error: print('Could not save')cur.execute(sql) print('Could not save')
Matches
try: cur.execute(sql, data) except: print("Could not save")
↓
A bare except catches every kind of error, including unrelated bugs, and hides the real cause. It should be except sqlite3.Error: so only database errors are handled.
Applying
Meanings
Term
except sqlite3.Error:
Meaning
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.
Practice
import sqlite3
Testing
Gaps
except :
Check Answer
Spots
1import sqlite3
2try

Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.

The 'Snowy Owl' badge — List Slicer, one of Cloodit's 106 collectible badges
Students earn collectable badges

Over 100 of them, across seven natural biomes.

Study Buddy
Students build a real study resource

Turns their work into revision material ready for Flash Cards and Exam study.

Diamond Dash — one of Cloodit's live, competitive Sprint games
Students lock in with Sprints

Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.

A Cloodit certificate of achievement, ready to personalise and print
Custom printable certificates

Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.

Quick Questions

1. Which code stops a failed INSERT from crashing the program with a long error message?
A. try: cur.execute(sql) except sqlite3.Error: print('Could not save') ✓
B. cur.execute(sql) print('Could not save')
Putting the SQL call inside try lets the except block catch sqlite3.Error and show a friendly message instead of a crash.
2. A student inserts a row with a primary key that already exists. Which error does sqlite3 raise?
A. sqlite3.ConnectionError
B. sqlite3.IntegrityError ✓
IntegrityError is raised when a constraint such as PRIMARY KEY, UNIQUE, NOT NULL or FOREIGN KEY is broken. sqlite3 has no ConnectionError class.
3. True or false: catching sqlite3.Error also catches an IntegrityError.
A. False
B. True ✓
IntegrityError is a subclass of sqlite3.Error, so except sqlite3.Error catches it along with other database errors.
4. Which line in an except block undoes the changes of a failed database operation?
A. conn.rollback() ✓
B. conn.commit()
rollback() cancels uncommitted changes. commit() would save them permanently.
5. Which except line correctly catches database errors?
A. except sqlite3.Error: ✓
B. except sqlite3.Error():
The exception class is named without brackets. Adding () is incorrect syntax in this form and a common slip.

Match the Pairs

except sqlite3.Error: → Catches any failed database call so the program can show a friendly message instead of crashing
except sqlite3.IntegrityError: → Catches an error caused by breaking a constraint, such as a duplicate primary key or a NOT NULL field left empty
Put the SQL call inside a try block so a constraint failure jumps to the except block instead of crashing the program → try: cur.execute(sql, data) except sqlite3.Error: print("Could not save")
After a failed change, undo the half-finished work with rollback() so the database is left in a safe state → except sqlite3.Error: conn.rollback() print("Change undone")
try: cur.execute(sql, data) except: print("Could not save") → A bare except catches every kind of error, including unrelated bugs, and hides the real cause. It should be except sqlite3.Error: so only database errors are handled.
try: cur.execute(sql, data) conn.commit() except sqlite3.Error: print("Failed") → The handler never calls conn.rollback(), so a failed change is not undone. It should call conn.rollback() before or after printing the message.

Key Term

except sqlite3.Error:
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.

Fill in the Blanks

1. try: cur.execute(sql, data) except sqlite3.Error:
Hint: Type the module and class name that catches any database error.
2. try: conn.commit() except sqlite3.Error:
Hint: Type the keyword that starts the block which runs when the database call fails.
3. except sqlite3.IntegrityError: print("That student ID is already used")
Hint: Type the specific error class raised when a constraint, like a duplicate primary key, is broken.
4. except sqlite3.Error: conn.rollback() print("Could not save. Try again.")
Hint: Type the connection method that undoes changes made since the last commit.
5. try: cur.execute(sql, data) except sqlite3.Error:
Hint: Type the keyword that starts the block holding the database call that might fail.

Spot the Error

Question 1
A import sqlite3
B try
C cur.execute(sql, vals)
D conn.commit()
E except sqlite3.Error:
F print('Save failed')
Line B — A try block must end with a colon. Without it Python raises a SyntaxError before the error handling can work. It should be try:
Question 2
A try:
B cur.execut(sql, vals)
C conn.commit()
D except sqlite3.Error:
E print('Insert failed')
Line B — 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).
Question 3
A import sqlite
B try:
C cur.execute(sql, vals)
D except sqlite3.IntegrityError:
E print('Duplicate ID')
Line A — The module is called sqlite3, not sqlite. Importing the wrong name causes a ModuleNotFoundError. It should be import sqlite3.
Question 4
A try:
B cur.execute(sql, vals)
C conn.commit()
D except sqlite3.error:
E print('Save failed')
Line D — Python is case-sensitive. The class is sqlite3.Error with a capital E, so sqlite3.error raises an AttributeError. It should be except sqlite3.Error:
Question 5
A try:
B cur.execute(upd, vals)
C conn.rollback()
D except sqlite3.Error:
E print('Update failed')
Line C — After a successful call the changes should be saved with conn.commit(). Calling rollback() here would undo the update. rollback() belongs in the except block.

Student with a class code? Join your class →