Home › Theme B › B2 › B2.1 › B2.1.3

B2.1.3 Handling errors with exceptions

SL + HLCommand term: Describe

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

Call:
Output

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?

User types days held:
Try: validtyped "twenty"file missinglogic bug
Console
Press Run.

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.

Click a row.

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: caught or crash?

Does the except clause catch the exception, or does the program crash?

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 1, task 3. A library program must never crash at the desk. Wrap the risky operations from tasks 1 and 2 in exception handlers. Download the starter, complete the four functions, run it, and compare with the expected output.

Expected output

20 None 2027 None 3.0 0.0 Catalogue file not found: no_such_file.txt Catalogue check done. 0

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

    Next task (B2.1.4): the fine calculator has a hidden logic bug. You will find it with trace output, breakpoints and test data.

    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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

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

    File: b2_1_3_average.py
    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
    List the more specific exceptions in separate except blocks.
    Model solution
    File: b2_1_3_average_solution.py
    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))
    
    Moderate

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

    File: b2_1_3_moderate.py
    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
    File: b2_1_3_moderate_solution.py
    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([]))
    
    Challenging

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

    File: b2_1_3_challenging.py
    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
    File: b2_1_3_challenging_solution.py
    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:

    1. Identify potential points of failure: unexpected inputs, resource unavailability and logic errors.
    2. Describe the role of exception handling in developing robust programs.
    3. Describe and trace the flow of control through try, except, else and finally in Python, and try, catch and finally in Java.
    4. 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 failureExamples in ShelfWiseTypical exception
    Unexpected input"twenty" typed for days; an empty title; a member ID with a letter where digits should beValueError, IndexError
    Resource unavailabilitycatalogue.txt deleted; school server offline; disk full; file locked by another userFileNotFoundError, PermissionError, ConnectionError
    Logic errorfine uses > instead of >=; average divides by the wrong countUsually 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]

    Award [1] each, up to [3]: unexpected/invalid input (e.g. text typed for a number of days); resource unavailability (e.g. the loans file is missing or the server is offline); logic error (e.g. fine calculated with the wrong condition); disk full / permission denied when saving; division by zero.

    2. Describe the role of exception handling in a program. [3]

    It detects runtime errors / exceptions as they occur [1]; it transfers control to handler code instead of letting the program crash [1]; so the program can recover gracefully, e.g. show a helpful message and re-prompt, or release resources [1].

    3. Describe the purpose of the finally block, with an example. [2]

    Code in finally always runs, whether or not an exception occurred or was handled [1]; e.g. closing a file or a database connection so the resource is released [1].

    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")
    12 / 0 raises ZeroDivisionError, so nothing is printed from the try block and "A" is skipped [1]; 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]

    Many logic errors raise no exception: the program runs normally but produces incorrect output [1]; so there is nothing for an except block to catch, and they must be found through testing / tracing / debugging [1].

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