B2.1.3 Handling errors with exceptions
SL + HLCommand term: Describe1. Follow the flow: try, except, else, finally
The same function runs with four different inputs. Step through and watch which blocks run (green), where the exception is raised (red), and which blocks are skipped. Notice that finally runs every time.
2. Crash or catch? The ShelfWise fine desk
Choose what goes wrong, then run the program with and without exception handling. Which failures can try/except rescue, and which can it not?
3. Name that exception
Each line fails when it runs. Choose the exception Python raises, then check.
4. Python try/except and Java try/catch
The syllabus requires both. Click any row to see the matching line in the other language and what it does.
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Classify the point of failure
Is it an unexpected input, a resource unavailability or a logic error? Streaks of 3+ score double.
7. 45-second speed round: caught or crash?
Does the except clause catch the exception, or does the program crash?
Expected output
Think about it
(1) Which point of failure does each function guard against? (2) Why is a bare except: a bad idea here? (3) average_loans(120, 30) returns 4.0, but the librarian expected 4: is that an exception, a logic error or neither?
Check my code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Safe division
Write safe_divide(a, b) that returns a / b. If b is zero, catch the ZeroDivisionError, print "cannot divide by zero" and return None. If either value is not a number, catch the TypeError and return None.
Starter file (write your code where it says pass # your code here):
def safe_divide(a, b):
pass # your code here
# ---- tests ----
print(safe_divide(10, 4))
print(safe_divide(5, 0))
print(safe_divide("5", 2))
Expected output when your code is correct:
2.5 cannot divide by zero None numbers only None
Hint
except blocks.Model solution
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
print("cannot divide by zero")
return None
except TypeError:
print("numbers only")
return None
# ---- tests ----
print(safe_divide(10, 4))
print(safe_divide(5, 0))
print(safe_divide("5", 2))
Task 2: Totalling messy scores
Scores typed by students arrive as strings, and some are wrong. Write total_scores(entries) that converts each entry with int(), adds the valid ones, and counts the invalid ones (not a whole number, or outside 0 to 100). Use try/except/else. Return (total, invalid_count).
Starter file (write your code where it says pass # your code here):
def total_scores(entries):
pass # your code here
# ---- tests ----
print(total_scores(["45", "x", "90", "101", " 7 ", "3.5", "-2"]))
print(total_scores([]))
Expected output when your code is correct:
(142, 4) (0, 0)
Hint
else runs only when the try block raised no exception.Model solution
def total_scores(entries):
total = 0
invalid = 0
for e in entries:
try:
value = int(e)
except ValueError:
invalid += 1
else:
if 0 <= value <= 100:
total += value
else:
invalid += 1
return total, invalid
# ---- tests ----
print(total_scores(["45", "x", "90", "101", " 7 ", "3.5", "-2"]))
print(total_scores([]))
Task 3: A config reader that raises errors
Write read_config(lines) that turns lines like "max_loans = 5" into a dictionary, ignoring blank lines and lines starting with #. For a line without = or with an empty key, raise a ValueError whose message includes the line number. Then write load(lines) that calls it inside try/except/else/finally: on an error print the message; in else print how many settings were read; in finally always print "done". Return the dictionary, or {} after an error.
Starter file (write your code where it says pass # your code here):
def read_config(lines):
pass # your code here
def load(lines):
pass # your code here
# ---- tests ----
print(load(["# ShelfWise settings", "max_loans = 5", "", "fine_per_day=0.20"]))
print(load(["max_loans = 5", "loan_days 14"]))
print(load([" = 3"]))
Expected output when your code is correct:
settings read: 2
done
{'max_loans': '5', 'fine_per_day': '0.20'}
config error: line 2: missing '='
done
{}
config error: line 1: empty key
done
{}
Hint
raise ValueError("message") throws the error; except ValueError as err catches it in the calling function.Model solution
def read_config(lines):
config = {}
for number, line in enumerate(lines, start=1):
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
raise ValueError(f"line {number}: missing '='")
key, value = line.split("=", 1)
if not key.strip():
raise ValueError(f"line {number}: empty key")
config[key.strip()] = value.strip()
return config
def load(lines):
result = {}
try:
result = read_config(lines)
except ValueError as err:
print("config error:", err)
else:
print("settings read:", len(result))
finally:
print("done")
return result
# ---- tests ----
print(load(["# ShelfWise settings", "max_loans = 5", "", "fine_per_day=0.20"]))
print(load(["max_loans = 5", "loan_days 14"]))
print(load([" = 3"]))
Learning objectives
By the end of this page you should be able to:
- Identify potential points of failure: unexpected inputs, resource unavailability and logic errors.
- Describe the role of exception handling in developing robust programs.
- Describe and trace the flow of control through try, except, else and finally in Python, and try, catch and finally in Java.
- Explain why exception handling cannot fix logic errors that raise no exception.
What is an exception?
An exception is an error that happens while a program is running (a runtime error), such as dividing by zero or opening a file that does not exist. If nothing handles it, the program stops and prints a traceback. A syntax error is different: the code cannot even start.
Points of failure
| Point of failure | Examples in ShelfWise | Typical exception |
|---|---|---|
| Unexpected input | "twenty" typed for days; an empty title; a member ID with a letter where digits should be | ValueError, IndexError |
| Resource unavailability | catalogue.txt deleted; school server offline; disk full; file locked by another user | FileNotFoundError, PermissionError, ConnectionError |
| Logic error | fine uses > instead of >=; average divides by the wrong count | Usually none: the program runs but gives wrong results; sometimes a ZeroDivisionError or IndexError |
The role of exception handling
- Lets a program detect a runtime error and respond to it instead of crashing: a graceful recovery.
- Gives the user a helpful message and a chance to try again, instead of a traceback.
- Keeps data safe: finally closes files and connections even when something fails.
- Separates the normal code (in try) from the error-handling code (in except), which makes programs clearer and more robust.
- It cannot fix logic errors that raise no exception: those need testing and debugging (B2.1.4).
The constructs
try:
days = int(input("Days held? ")) # code that might fail
fine = 10 / days
except ValueError: # runs only if a ValueError happens
print("Please type a whole number.")
except ZeroDivisionError: # a second, different handler
print("Days cannot be 0.")
else: # optional: runs only if no exception
print("Fine:", fine)
finally: # optional: ALWAYS runs
print("Back to menu")
- When a line in try raises an exception, the rest of the try block is skipped; Python checks each except in order and runs the first one that matches.
- If no except matches, finally still runs, then the exception passes up (propagates) to the caller.
- Catch specific exceptions. A bare
except:also hides bugs you need to see. raise ValueError("copies cannot be negative")lets your own code signal an error.
In Java
try {
int days = Integer.parseInt(text);
int share = 10 / days;
} catch (NumberFormatException e) {
System.out.println("Please type a whole number.");
} catch (ArithmeticException e) {
System.out.println("Days cannot be 0.");
} finally {
System.out.println("Back to menu");
}
Same idea, different keyword: Java catch = Python except. Both have finally.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Identify three potential points of failure in a program that records library loans. [3]
2. Describe the role of exception handling in a program. [3]
3. Describe the purpose of the finally block, with an example. [2]
4. The user enters 0. State the output. [3]
try:
n = int(input())
print(12 / n)
except ValueError:
print("A")
except ZeroDivisionError:
print("B")
finally:
print("C")
print("D")
B [1]; then C and D [1]. Output: B, C, D on separate lines.5. Explain why exception handling alone cannot deal with all logic errors. [2]
6. Construct a Python function load_loans(filename) that returns the file's contents, prints a message and returns an empty string if the file does not exist, and always prints "Done". [4]
try: block containing open(filename) and read() [1]; except FileNotFoundError: (specific exception) [1] with a message and an empty-string result [1]; finally: print("Done") and the result returned [1].