IB Computer Science HL · Year 2 · Lesson 10

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.

Paper 250 minutesB2.1.3 · B2.1.4 · B2.5.1
Today’s targets

What you need to be able to do

2 / 12
  • 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.
B2.1.3B2.1.4B2.5.1
Paper 2 habitRead the command term and the data given. A technically correct answer still needs to answer the exact task.
Learn + retrieve

Rapid Recall Deck

3 / 12

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

B2.1.3 · Describe

Different failures need different responses

4 / 12

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.

A — can a specific runtime exception be caught?
B — can the unavailable resource be handled or reported?
C — would a logic error necessarily raise an exception?

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.

try / except / finally

Handle a bad input without hiding the cleanup

5 / 12

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.

try — place the risky conversion inside it.
except ValueError — handle invalid integer text.
finally — run the final message regardless of success or failure.
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.

Do not misuse exceptionsException handling manages exceptional runtime conditions. It does not prove that the algorithm's logic is correct.
B2.1.4 · Debugging

Choose a debugging technique that exposes the state

6 / 12

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.

Trace the values of i and total.
Identify which element is never processed.
Repair the loop without changing the List.

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.

B2.5.1 · File processing

Sequential text files: read, write, append and close

7 / 12

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.

Construct file processing

Combine a file resource with exception handling

8 / 12

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.

Initialize a variable so finally can tell whether a file was opened.
try — open, readline, print.
except FileNotFoundError — report the unavailable resource.
finally — close only an opened file.
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()
B2 checkpoint · Concepts

Retrieve the decisions behind the code

9 / 12

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.

  1. Stack; pop.
  2. Queue; dequeue.
  3. A static structure has fixed allocated capacity; a dynamic structure can resize during execution, giving greater flexibility but potentially adding resizing/allocation overhead.
  4. 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.
  5. 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.
  6. The base case stops further recursive calls and provides a result that lets pending calls return.
B2 checkpoint · Python

Construct and trace without hidden assumptions

10 / 12

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

  1. label = "A" is a one-character string representing char data; count is int; rate is a floating-point representation of decimal data; ready is bool. Any of them can be local if created inside a function.
  2. code[5:7]
  3. Validation must happen before the discount calculation so invalid data is not used to produce an apparently valid result.
  4. count = 0
    for score in scores:
        if score >= 60:
            count += 1

    Final count: 2.

  5. def double(value):
        return value * 2
  6. low=0, high=4, mid=2, so the first compared value is 12. Because 19 is larger, the next search range starts at index 3.
  7. Compare 7 and 3; swap → [3, 7, 5].
  8. step(2) → step(1) → step(0).
2027 Case Study · Formal launch

Generative AI for image creation — a diffuse vision

11 / 12

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.

First research noteStart with Challenge 1. Find one credible source that helps explain why iterative denoising can demand substantial computation and record one quality/efficiency trade-off to investigate further.
Homework

Finish the learning cycle

12 / 12

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.