ICS3U Computer Science • Ontario Grade 11

Revision sheet: debugging and testing, errors, test plans and exceptions (ICS3U)

This sheet is not a summary of the debugging and testing chapter of ICS3U, Introduction to Computer Science, Grade 11: you already have your notes.

What the sheet covers

It answers one question only, what makes students lose marks when they classify an error, read a message, fill in a test plan or handle an exception, and which precise gesture avoids each loss.

The code is in Python 3. Every message quoted on this sheet is the one Python 3.13 printed for the program shown, with the folder in front of the file name cut; older versions of Python 3 word some messages differently.

  • 8 mistakes that cost marks
  • 3 figures
  • 15 min reading
Do the chapter's exercises

The thread of the chapter

An error is found by the way it shows itself: a syntax error stops the program before its first line runs, a run-time error stops it at the line where Python detects it, which is not always the line that caused it, and a logic error stops nothing: it is found by comparing the actual outcome with an expected outcome computed by hand, on normal, boundary and invalid inputs.

Topics covered

  • Syntax error
  • Run-time error
  • Logic error
  • Traceback
  • Exception
  • Tracing technique
  • Debugging output
  • Test plan
  • Boundary value
  • Equivalence class
  • Exception handling
  • Guard condition

The essentials

Three kinds of errors, told apart by when they show

  • • Syntax error: a rule of the language is broken (a missing colon, comma or parenthesis, a wrong indentation). Python reads the whole file before running it and refuses it: no line runs, not even the first prompt.
  • • Run-time error: the file is accepted, the lines run one by one, and Python stops at the first line it cannot carry out (a division by zero, int() of a word, a name never assigned). It prints a traceback.
  • • Logic error: every line runs and no message appears, but the result is wrong. A test, or a trace, compared with an expected outcome computed by hand shows it.
  • • The debugging loop: run, read what appears, fix ONE thing, run again; when the program runs, run the whole test plan.
Run the programDoes line 1 run?Syntax errorfix the line named,or the line above itnoTraceback?yesRun-time errorlast line, then the last File line,then where the value came fromyesEvery test passes?noLogic errortrace, or print the variables:the first wrong valuenoProgram ready:run the whole plan after each fixyesafter the fix, run again
Three questions in a fixed order: does the program start, does it stop with a traceback, does every test pass; each no or yes on the right names the kind of error and where to look.

A test plan, column by column

  • • Scenario: the case tested, in words (normal, on the boundary, just past it, not valid).
  • • Input: the exact value typed or passed.
  • • Expected outcome: computed from the specification, BEFORE the run, never copied from the program.
  • • Actual outcome: what the program printed or returned, copied as it appears.
  • • Result: pass when expected and actual agree, fail otherwise.
  • • The inputs: one typical value per class, both sides of every boundary, an extreme case (0, an empty entry), and at least one entry that is not valid.

A plan whose expected column was filled from the program's output can only pass.

The rules in table form

Each row reads from left to right: the assumptions, then the result. A red cell is not an answer, it is the finding that the form settles nothing and the instruction to rewrite it. Every case is followed by a worked example.

The messages of the course, last line first

Each line of code below was run in Python 3.13; the last column is the last line of the message it printed.

ExceptionA line that raises itLast line of the message
ZeroDivisionError print(12 / 0) ZeroDivisionError: division by zero

Example: A / whose right side is 0, here or after a count that stayed at 0.

ZeroDivisionError print(12 // 0) ZeroDivisionError: integer division or modulo by zero

Example: The same error with // or %, worded differently: 12 // 5 gives 2, 12 // 0 has no value.

ValueError print(int("ten")) ValueError: invalid literal for int() with base 10: 'ten'

Example: Right type, a string, wrong value: int('10') gives 10, int('ten') has letters.

ValueError print(float("4,5")) ValueError: could not convert string to float: '4,5'

Example: A comma typed as the decimal mark: float('4.5') gives 4.5.

ValueError import math ; print(math.sqrt(-4)) ValueError: math domain error

Example: math.sqrt(4) gives 2.0; math.sqrt(-4) has no real value, and it is a ValueError too, like a typing error.

TypeError print("Score: " + 85) TypeError: can only concatenate str (not "int") to str

Example: A string and a number joined by +: print('Score:', 85) prints Score: 85 with no error.

TypeError print("30" > 25) TypeError: '>' not supported between instances of 'str' and 'int'

Example: A value from input() never converted: once converted, int('30') > 25 is True.

NameError total = 5 ; print(totl) NameError: name 'totl' is not defined. Did you mean: 'total'?

Example: A misspelled name: print(total) prints 5, totl was never assigned.

IndexError print([4, 8, 1][3]) IndexError: list index out of range

Example: [4, 8, 1] has 3 cells, indices 0 to 2: [4, 8, 1][2] is 1, index 3 does not exist.

SyntaxError x = 5 ; if x > 3 ; print(x) SyntaxError: expected ':'

Example: Found before the run: no line runs, not even line 1.

none: logic error average = a + b / 2 no message at all no message

Example: With a = 70 and b = 90, it prints 115.0 and stops normally.

Same form, other result: With a = 0 and b = 0, the same line prints 0.0, the right average: one passing test proves nothing.

What to do: Compute the expected outcome by hand, (70 + 90) / 2 = 80.0, and compare: the test fails.

The exception names the kind of problem; the line named is where Python noticed it.

The mistakes that cost marks

These are the errors I correct most often in session. Each one costs marks on a paper, even when the reasoning behind it is right.

1. A silent run taken for a correct program

the marks of every question that asks for an output

What not to write

“My program ran with no error message, so it is correct.”

What to write

“The run rules out syntax and run-time errors for this input. The test with the expected outcome computed by hand says whether the result is right.”

Why: A logic error breaks no rule of the language: Python has nothing to report.

2. Fixing the line the message names

1 to 2 marks, and a run-time error turned into a logic error

What not to write

“temp = input('Temperature: '), then if temp > 30: stops with a TypeError on line 2, so I write if temp > '30': on line 2.”

What to write

“The string comes from line 1: temp = int(input('Temperature: ')). Comparing with '30' removes the message and compares text: 9 typed gives a heat alert.”

Why: The message names the line where Python detected the problem; the faulty value was created where input() was read.

3. A traceback read from the top

1 mark, and time lost on a line that is correct

What not to write

“The traceback names line 4 first, so the error is on line 4.”

What to write

“The last File line names where Python stopped, line 3 in speed; line 4 is the call that led there. The last line gives the exception: ZeroDivisionError: float division by zero.”

Traceback (most recent call last):File "cycling.py", line 4, in <module>print(speed(12, 0))File "cycling.py", line 3, in speedreturn km / hoursZeroDivisionError: float division by zero1. read first: what went wrong2. where Python stopped: line 3, in speed3. the call that led there: line 4
Read it from the bottom: the exception, then the last File line, then the call above it. The ~ and ^ marks that Python prints under each line of code are left out here.

Why: Python prints the chain of calls most recent call last: the bottom is where the error happened.

4. A plan of typical values only

1 to 2 marks for the plan, and a bug left in the program

What not to write

“My tests sunflower42, abc and a 70-character password all pass, so the length rule works.”

What to write

“The rule has two boundaries, 8 and 64 characters: I test 7 and 8, 64 and 65. The test with 8 characters fails: len(pw) > 8 refuses it.”

Why: A < written for <= is wrong on the boundary value only; a value far from the boundary passes either way.

5. The divisor tested after the division

the whole question: with 0 games, the program stops before the test

What not to write

“average = pins / games, then if games == 0: print('No game played').”

What to write

“if games > 0: average = pins / games, else print('No game played'): the guard comes before the division.”

Why: Python runs the lines in order: the division by zero stops the program before the if is reached.

6. A bare except that hides the real error

1 to 2 marks: the program prints Please type a number to a user who did

What not to write

“try: with the inputs and the division inside, then except: print('Please type a number'), so every mistake is handled.”

What to write

“The try holds the inputs only, with except ValueError:. A division by zero then shows its own message, or is prevented by a guard.”

Why: except: alone catches every exception, so a message written for one problem is shown for another.

7. One passing test taken as a proof

1 mark, and a function wrong for half of the even numbers

What not to write

“is_multiple_of_4(n) returns n % 2 == 0. My test with 8 gives True, so it works.”

What to write

“8 is a multiple of 4 and of 2: the test cannot tell the two rules apart. With 6, it returns True instead of False: the test fails.”

Why: A test that passes proves the program right for that input; choose inputs where a wrong program would give another answer.

8. A syntax error expected to let the top of the file run

time lost tracing lines that never ran

What not to write

“Lines 1 to 9 must have run, since the message is about line 10.”

What to write

“A syntax error stops the whole file: if not even the first prompt appeared, the file was refused, and the line named is where to look.”

Why: Python accepts or refuses the whole file before running it. A missing closing parenthesis is named at the line where it opens since Python 3.10; older versions often named the next line.

Which method to choose

What the screen shows, and where to look

Look at what appeared before the program stopped, not at what you expected.

  • If nothing at all appeared, not even the first prompt, and a SyntaxError or IndentationError is printed → a syntax error: look at the line named, then at the line above it

    Example: SyntaxError: expected ':' on if x > 3

  • If some lines ran, then a traceback ends with an exception → a run-time error: read the last line, then the last File line, then ask where the faulty value was created

    Example: TypeError on line 6, string read on line 2

  • If the program ended normally with a result → compare it with the expected outcome computed by hand; if they differ, a logic error: trace, or print the variables, and find the first wrong value

    Example: print('DEBUG', tax, tip, total) after the line that computes them

  • If every test of the plan passes → check that the plan holds both sides of every boundary and an entry that is not valid, then keep it to run again after each change

    Example: 7 and 8, 64 and 65 characters, and an empty entry

Fix one error per run: a syntax error hides every other error of the file, and a run-time error hides the lines after it.

How the answer is expected to be written

A marker ticks steps. Here they are in order, with the concluding sentence expected word for word.

Filling in a test plan on a unit test

When to use it: « Write a test plan for this program », « Complete the table: expected, actual, pass or fail »

  1. 1 Split the inputs into classes from the specification, and list the boundaries between them.
  2. 2 Choose the inputs: both sides of each boundary, one typical value per class, an extreme case, an entry that is not valid.
  3. 3 Compute each expected outcome from the specification, before reading the code.
  4. 4 Trace or run the program and copy each actual outcome as it appears, error messages included.
  5. 5 Conclude pass or fail on each row, then say which line causes each fail.

Concluding sentence

“Test 4: input maple123, 8 characters, expected Accepted, actual Rejected: fail. Line 2 tests len(pw) > 8 and must test len(pw) >= 8.”

The trap: Copying the program's output into the expected column: the plan then passes by construction.

Marking: A common split: 1 mark per complete row, 1 for the choice of boundary values, 1 for the conclusion.

Explaining a bug in a written answer

When to use it: « Identify and correct the error », « Why does this program crash? »

  1. 1 Name the kind of error: syntax, run-time or logic.
  2. 2 For a run-time error, quote the exception and the line it names; for a logic error, give the input, the expected and the actual outcome.
  3. 3 Point to the line that causes it, which may be an earlier line.
  4. 4 Write the corrected line.
  5. 5 Say which test now passes, and add one that would catch the error again.

Concluding sentence

“Run-time error: TypeError on line 2, because temp is a string read on line 1. Line 1 becomes temp = int(input('Temperature: ')); the test 31 now gives Heat alert.”

The trap: Writing only the corrected line: the kind of error and the reason carry marks too.

Marking: A common split: 1 mark for the kind, 1 for the cause, 1 for the correction.

Check before you hand in

Five minutes of checking recover more marks than one more problem started in a hurry.

  • The expected column first

    Cover the actual column with your hand: every expected outcome must come from the specification.

    Expected Accepted for 8 characters, because the rule says 8 to 64.

  • Both sides of every boundary

    For each number in the specification, look for two tests, one on each side.

    A cap at 40 days asks for 40 and 41.

  • One entry that is not valid

    Every int(input()) or float(input()) needs a test with letters.

    twelve typed for a number of people.

  • Guards above their risky line

    Point to every / and every math.sqrt: the if that protects it must be above it, not below.

    if games > 0: on the line before average = pins / games.

The typical problem, taken apart

A test plan for a password length rule

A sign-up page accepts a new password of 8 to 64 characters, both included, and rejects any other length with the message Rejected: 8 to 64 characters. Build the test plan, run it on the program below, and correct the program.

password.py
pw = input("New password: ")                # line 1
if len(pw) > 8 and len(pw) <= 64:           # line 2
    print("Accepted")                       # line 3
else:                                       # line 4
    print("Rejected: 8 to 64 characters")   # line 5

Step 1

Classes from the specification: too short, 0 to 7 characters; accepted, 8 to 64; too long, 65 or more. Every entry of input() is a string, so a length is always defined.

Why

The classes come from the words of the specification, before the code is read.

Step 2

Boundaries: 7 | 8 and 64 | 65, so four values: maple12 (7), maple123 (8), a password of 64 characters and one of 65.

Why

A < written for <= is wrong on the boundary value only: each boundary is tested on both sides.

Step 3

Add a typical value, sunflower42 (11 characters), and the extreme case, an empty entry (0 characters): six tests in all.

Why

The typical value checks the normal case; the empty entry is the case a user makes by pressing Enter.

Step 4

Expected outcomes from the specification: Accepted for 11, 8 and 64 characters; Rejected for 0, 7 and 65.

Why

Written before the run, they are a judgement on the program, not a copy of it.

Step 5

Run: test 4, maple123, prints Rejected: 8 to 64 characters where Accepted is expected. The other five pass. Line 2 tests len(pw) > 8, which refuses 8: it becomes if len(pw) >= 8 and len(pw) <= 64:, and the six tests pass.

TestScenarioLengthExpectedActualResult1Typical11AcceptedAcceptedPass2Empty entry0RejectedRejectedPass3Just too short7RejectedRejectedPass4Shortest valid8AcceptedRejectedFail5Longest valid64AcceptedAcceptedPass6Just too long65RejectedRejectedPassThe plan, run: one test fails, on a boundary

Why

The fail names the boundary, and the boundary names the line: the comparison that uses 8.

The conclusion, written out

“Test 4, 8 characters, fails: line 2 must use >= 8. After the fix, the six tests of the plan pass.”

The classic mistake on this problem: A plan with sunflower42, abc and a password of 70 characters passes the faulty program: three tests, three passes, and the bug of 8 characters is still there.

Learn by heart

  • • Syntax error: the file is refused, no line runs.
  • • Run-time error: some lines run, then a traceback.
  • • Logic error: no message; a test against a value computed by hand shows it.
  • • A traceback is read from the bottom: exception, last File line, then the calls.
  • • The line named is where Python noticed; the cause may be above.
  • • Expected outcome from the specification, before the run.
  • • Test both sides of every boundary, and one entry that is not valid.
  • • A guard goes above the risky line; a try holds only the line that can fail, with except ValueError:.

Frequently asked questions

What is the difference between a syntax error, a run-time error and a logic error?

A syntax error breaks a rule of the language, so Python refuses the whole file and no line runs. A run-time error happens while the program runs: some lines run, then Python stops at a line it cannot carry out and prints a traceback. A logic error gives no message at all: the program runs to the end and prints a wrong result, which shows when you compare it with an expected outcome computed by hand.

How do you read a Python traceback?

Start at the bottom. The last line gives the type of the exception and a message, such as a division by zero. The last File line above it gives the line where Python stopped and the function it is in. The File lines higher up are the calls that led there. Then ask where the faulty value was created, which may be an earlier line.

What should a test plan include in ICS3U?

Each row gives a scenario, the input, the expected outcome computed from the specification before the run, the actual outcome copied from the run, and pass or fail. Choose one typical value per class of inputs, the values on both sides of every boundary, an extreme case such as zero or an empty entry, and at least one entry that is not valid.

Why does my program stop on a line that looks correct?

Because the message names the line where Python detected the problem, not always the line that caused it. A value read with input and never converted is a string, and it only fails later, when it is divided or compared with a number. Follow the variable named in the message back to the line where it received its value, and fix it there.

Should I use try and except or an if statement to avoid a crash?

Use an if, a guard placed before the risky line, when you can test the problem first, such as a number of people that must be above zero before a division. Use try and except ValueError around the conversion of what the user typed, since you cannot test text before converting it. Keep the try block short, and avoid a bare except, which hides other errors.

Mark this sheet as read or add it to your favourites: a free account, no password, keeps your read sheets and favourites from one visit to the next, tells you which chapter to tackle next and lets you ask for the method or exercise you are missing. Create your space, an email is enough.

Practise it

Corrected exercises: Debugging and testing: errors, test plans and exceptions, ICS3U

A method is proved on a paper, not on a sheet. The set for the same chapter takes each of these traps into a problem, with the solution written out step by step.

  • 10 corrected exercises
  • 100 points
  • 150 minutes
Do the exercises
Something missing from this sheet? A method, a trap, an exercise to practise it, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Revision sheet published at www.letuteurscientifique.ca/en/fiches/ics3u-debugging-testing. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session.

Site by Studio Squalli