Handling database errors in code

Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.

Handling database errors in code

Name:
Date:
Class:

Quick Questions

Shade in the A or B circle for each question.

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')
2. A student inserts a row with a primary key that already exists. Which error does sqlite3 raise?
A sqlite3.ConnectionError
B sqlite3.IntegrityError
3. True or false: catching sqlite3.Error also catches an IntegrityError.
A False
B True
4. Which line in an except block undoes the changes of a failed database operation?
A conn.rollback()
B conn.commit()
5. Which except line correctly catches database errors?
A except sqlite3.Error:
B except sqlite3.Error():

Match the Pairs

Draw a line connecting each item on the left to its match on the right.

Left columnRight column
1except sqlite3.Error: ACatches any failed database call so the program can show a friendly message instead of crashing
2except sqlite3.IntegrityError: BA 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.
3Put the SQL call inside a try block so a constraint failure jumps to the except block instead of crashing the program CThe handler never calls conn.rollback(), so a failed change is not undone. It should call conn.rollback() before or after printing the message.
4After a failed change, undo the half-finished work with rollback() so the database is left in a safe state Dtry: cur.execute(sql, data) except sqlite3.Error: print("Could not save")
5try: cur.execute(sql, data) except: print("Could not save") ECatches an error caused by breaking a constraint, such as a duplicate primary key or a NOT NULL field left empty
6try: cur.execute(sql, data) conn.commit() except sqlite3.Error: print("Failed") Fexcept sqlite3.Error: conn.rollback() print("Change undone")

Definitions

except sqlite3.Error:

Fill in the Blanks

Complete each line of code by filling in the missing parts.

1.
try: cur.execute(sql, data) except _____________:
2.
try: conn.commit() ______ sqlite3.Error:
3.
except sqlite3.______________: print("That student ID is already used")
4.
except sqlite3.Error: conn.________() print("Could not save. Try again.")
5.
___: cur.execute(sql, data) except sqlite3.Error:

Spot the Error

Shade in the letter of the line that contains an error.

Question 1
A import sqlite3
B try
C cur.execute(sql, vals)
D conn.commit()
E except sqlite3.Error:
F print('Save failed')
Question 2
A try:
B cur.execut(sql, vals)
C conn.commit()
D except sqlite3.Error:
E print('Insert failed')
Question 3
A import sqlite
B try:
C cur.execute(sql, vals)
D except sqlite3.IntegrityError:
E print('Duplicate ID')
Question 4
A try:
B cur.execute(sql, vals)
C conn.commit()
D except sqlite3.error:
E print('Save failed')
Question 5
A try:
B cur.execute(upd, vals)
C conn.rollback()
D except sqlite3.Error:
E print('Update failed')

Answer Key

Handling database errors in code
Section A: Quick Questions
Q1
A — try: cur.execute(sql) except sqlite3.Error: print('Could not save')
Q2
B — sqlite3.IntegrityError
Q3
B — True
Q4
A — conn.rollback()
Q5
A — except sqlite3.Error:
Section B: Match the Pairs
Q1
except sqlite3.Error: → Catches any failed database call so the program can show a friendly message instead of crashing
Q2
except sqlite3.IntegrityError: → Catches an error caused by breaking a constraint, such as a duplicate primary key or a NOT NULL field left empty
Q3
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")
Q4
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")
Q5
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.
Q6
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.
Section C: Definitions
Q1
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.
Section D: Fill in the Blanks
Q1
try: cur.execute(sql, data) except sqlite3.Error:
Q2
try: conn.commit() except sqlite3.Error:
Q3
except sqlite3.IntegrityError: print("That student ID is already used")
Q4
except sqlite3.Error: conn.rollback() print("Could not save. Try again.")
Q5
try: cur.execute(sql, data) except sqlite3.Error:
Section E: Spot the Error
Q1
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:
Q2
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).
Q3
A — The module is called sqlite3, not sqlite. Importing the wrong name causes a ModuleNotFoundError. It should be import sqlite3.
Q4
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:
Q5
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.