Error handling (try/except)

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? values = [4, 5, 2, 3] total = 0 for v in values: try: total += 10 // v except ZeroDivisionError: total += 33 print(total)

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Error handling (try/except) explained

    Error handling lets a Python program deal with a problem, such as a missing number or a division by zero, without crashing. The risky code goes in a try block, and the response goes in an except block. If an error occurs inside try, Python skips the rest of that block and runs the matching except block instead.

    An exception is the error object Python raises when something goes wrong. Name the exception type after except, such as ValueError, so that only the errors you expect are caught. A bare except: catches everything and can hide bugs. A finally block runs whether or not an error occurred, which suits cleanup such as closing a file.

    try:
        n = int(input("Number: "))
        print(100 / n)
    except ValueError:
        print("That is not a whole number.")
    except ZeroDivisionError:
        print("Cannot divide by zero.")
    finally:
        print("Done")
    

    Worked example

    Trace the code above with the input 0.

    1. int("0") succeeds, so n is 0.
    2. 100 / 0 raises ZeroDivisionError, and Python jumps out of the try block.
    3. The ValueError clause does not match, so Python checks the next clause.
    4. ZeroDivisionError matches, so "Cannot divide by zero." is printed.
    5. finally runs, so "Done" is printed last.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? values = [2, 4, 1] total = 0 for v in values: try: total += 28 // v except ZeroDivisionError: total += 34 print(total)

    • Medium

      What does this Python code print? data = ["7", "1", "6", "7", "x", "6"] total = 5 for s in data: try: total += int(s) except ValueError: total -= 2 print(total)

    • Hard

      What does this Python code print? def check(n): count = 0 try: result = 49 // n except ZeroDivisionError: count += 6 else: count += 2 finally: count += 6 return count total = 0 for n in [5, 5, 3]: total += check(n) print(total)