Exception Handling, Debugging, File Processing and B2 Checkpoint
Construct robust Python file-processing code, diagnose failures, and consolidate the first B2 programming block before launching the 2027 case-study research strand.
What you need to be able to do
- describe unexpected input, resource unavailability and logic errors as potential failure points;
- use Python try, except and finally appropriately;
- construct and use trace tables, breakpoints, print statements and step-by-step execution as debugging techniques;
- construct sequential text-file processing in read, write and append modes using open(), read(), readline(), write() and close();
- retrieve and apply B2.1–B2.4 skills from Lessons 1–9 in Paper 2-style tasks;
- launch the 2027 case-study research strand through the four HL challenge areas.
Rapid Recall Deck
Attempt each card first. If a term is new, flip and study it, then answer it again without looking. Mark only secure recall as “Know it”.
Different failures need different responses
Unexpected input
Example: converting "abc" to an integer raises a runtime exception.
Resource unavailable
Example: a required text file does not exist or cannot be opened.
Logic error
The program runs but produces an incorrect result because the algorithm or condition is wrong.
Match the technique to the failure
For each case, state whether exception handling, debugging/testing, or both are needed, and justify briefly:
A. int(text) receives non-numeric input.
B. A program attempts to open a file that may not exist.
C. A program runs without an exception but calculates the wrong total because one List item is skipped.
Unexpected input: exception handling can catch a conversion error, and testing should verify the response. Unavailable file: exception handling can catch the file-opening failure and provide a controlled response. Logic error: debugging/testing is essential because the program may run normally without raising an exception.
Handle a bad input without hiding the cleanup
Construct the missing handling
Complete a program that converts text to an integer. If conversion fails, print "Invalid integer". In all cases, print "Finished" from a finally block.
text = "12x"
try:
value = int(text)
print(value)
except ValueError:
print("Invalid integer")
finally:
print("Finished")For text = "12x", the output is Invalid integer followed by Finished.
Choose a debugging technique that exposes the state
Trace table / step-by-step
Track variable values and control flow one instruction at a time.
Breakpoint
Pause execution at a chosen line and inspect the current program state.
Print statements
Temporarily display values or checkpoints to show what the program is doing.
Testing
Use selected inputs and expected outputs to expose incorrect behaviour, including logic errors.
numbers = [10, 20, 30]
total = 0
for i in range(1, len(numbers)):
total += numbers[i]
print(total)Debug the logic error
The intended output is the sum of every value in numbers. The program prints 50.
The loop starts at index 1, so numbers[0] is skipped. A trace table or breakpoint would show i taking only 1 and 2. One repair is:
for i in range(len(numbers)):
total += numbers[i]The corrected output is 60.
Sequential text files: read, write, append and close
Read · "r"
file = open("notes.txt", "r")
text = file.read()
file.close()Write · "w"
file = open("notes.txt", "w")
file.write("New file")
file.close()Existing contents are replaced.
Append · "a"
file = open("notes.txt", "a")
file.write("\nMore")
file.close()New data is added to the end.
Choose the mode
A program must preserve all existing log entries and add one new entry. Which mode should it use, and why would "w" be wrong?
Use append mode "a" because the new entry must be added after the existing contents. Write mode "w" would replace the existing file contents rather than preserve them.
Combine a file resource with exception handling
Construct a safe first-line reader
Write code that attempts to open "scores.txt" for reading, reads one line with readline(), and prints it. If the file cannot be found, print "File unavailable". Use finally to close the file only if it was opened successfully.
file = None
try:
file = open("scores.txt", "r")
line = file.readline()
print(line)
except FileNotFoundError:
print("File unavailable")
finally:
if file is not None:
file.close()Retrieve the decisions behind the code
1. A structure must process the most recently added item first. Name the suitable structure and the operation that removes the next item.
2. A printer must normally process jobs in arrival order. Name the suitable structure and the operation that removes the next job.
3. Compare static and dynamic structures in terms of resizing and flexibility.
4. A List is sorted by student name. Explain why binary search can find a name efficiently, but cannot automatically be used to find a student from an unsorted ID field.
5. Describe the scalability difference between O(n) and O(n²).
6. Explain why a recursive function needs a base case.
- Stack;
pop. - Queue;
dequeue. - A static structure has fixed allocated capacity; a dynamic structure can resize during execution, giving greater flexibility but potentially adding resizing/allocation overhead.
- Binary search requires ordering/indexing by the search key. Name ordering supports name comparisons; an unsorted ID field does not provide the ordering needed to discard half safely.
- O(n) grows roughly in proportion to input size, while O(n²) grows roughly with its square, so quadratic work becomes much more expensive as n grows.
- The base case stops further recursive calls and provides a result that lets pending calls return.
Construct and trace without hidden assumptions
1 · Variables/data types. Given label = "A", count = 3, rate = 0.5 and ready = True, identify the Python representation/type of each value and state which of these variables could be local inside a function.
2 · Substring. Given code = "IBCS-HL-2027", construct an expression that extracts "HL".
3 · Sequence. A program must validate that price >= 0 before applying a discount. State which action must occur first and why.
4 · Selection + loop. Given scores = [61, 42, 88], construct code that counts how many scores are at least 60.
5 · Function. Construct double(value) so it returns twice the input.
6 · Search. Given sorted data = [4, 8, 12, 19, 25], trace the first comparison made by binary search for target 19.
7 · Sort. Trace the first bubble-sort comparison on [7, 3, 5] and state the List immediately afterward.
8 · Recursion. Given def step(n): with base case n == 0 and recursive call step(n - 1), state the arguments in the call chain for step(2).
label = "A"is a one-character string representing char data;countis int;rateis a floating-point representation of decimal data;readyis bool. Any of them can be local if created inside a function.code[5:7]- Validation must happen before the discount calculation so invalid data is not used to produce an apparently valid result.
count = 0 for score in scores: if score >= 60: count += 1Final count: 2.
def double(value): return value * 2low=0, high=4, mid=2, so the first compared value is12. Because 19 is larger, the next search range starts at index 3.- Compare 7 and 3; swap →
[3, 7, 5]. step(2) → step(1) → step(0).
Generative AI for image creation — a diffuse vision
Visionary Studios is evaluating generative-AI approaches for creative image production. HL preparation is driven by four official challenge areas rather than by memorizing one prepared essay.
1 · Diffusion compute
Investigate iterative denoising and the computational demands of producing high-quality images.
2 · Training data
Investigate dataset curation, intellectual property, bias and bias mitigation.
3 · GAN balance · HL
Investigate generator/discriminator balance, training instability and mode collapse.
4 · Hybrid models · HL
Evaluate trade-offs among diffusion, GAN, VAE and flow-based approaches when models are combined.
Finish the learning cycle
IA — main task
If the IA problem/planning is sufficiently defined, begin or continue development with an evidence log. Record meaningful implementation decisions and tests rather than adding complexity for its own sake.
Syllabus — short retrieval
Redo the two B2 checkpoint pages without Reveal. Any item that still feels slow becomes a targeted review item rather than a reason to reread the whole unit.
2027 Case Study — research checkpoint
Save the source you found for the diffusion-compute challenge. Record: source title/author or organization, one evidence-based finding, and one sentence explaining why the finding matters to Visionary Studios.