Python 3D Academyবাংলা

Catching errors with try and except

🌍 In real life. A circus acrobat practises over a safety net. Most of the time the net isn't needed, but if she slips, the net catches her and the show goes on, instead of ending in disaster. The net is set up only under the risky part of the act.

In Python, try and except are that net.

The idea in one sentence: put risky code in a try block, and if it raises the error named in except, Python runs the except block instead of crashing, then carries on.

Its words:

  • exception: Python's name for an error raised while the program runs
  • raise: what Python does when something goes wrong, like int("abc")
  • catch: handle a raised error with except
  • try / except ValueError:: the risky part, and what to do if that error happens

Step by step, when the user types abc:

  1. Python starts the try block: int("abc") raises a ValueError.
  2. The rest of the try block is skipped.
  3. except ValueError: matches, so its block runs: "That's not a number".
  4. Python carries on after the try, and prints "Bye".
text = input("A number: ")
try:
    n = int(text)
    print("Double is", n * 2)
except ValueError:
    print("That's not a number")
print("Bye")
Run it and type abc: the except block runs. Run it again and type 21: then the except block is skipped.

Name the error you expect, like except ValueError or except ZeroDivisionError. Then an error you didn't expect, a real bug, still shows up instead of being hidden.

people = 0
try:
    share = 12 / people
    print("Each gets", share)
except ZeroDivisionError:
    print("Nobody to share with!")

Why name the error? Catching only what you expect keeps real bugs visible. If you catch everything, a typo like totl instead of total (a NameError) would be "handled" by your message about a bad number, and you'd never find it.

What it costs. A try block costs almost nothing when no error happens. Raising and catching an error takes a little longer, which is fine for rare problems like a mistyped answer.

Mistakes and edge cases.

  • try without except. A try: on its own gives SyntaxError: expected 'except' or 'finally' block.
  • Catching too much. except Exception: around code with a typo hides the NameError behind your own message.
  • Too much code in the try. Only wrap the lines that can fail in the way you expect; otherwise a different error from another line gets caught by mistake.
  • The wrong error name. except ValueError: doesn't catch a ZeroDivisionError, which still stops the program.

Quiz

  1. What does this print?

    try:
        n = int("5")
        print(n + 1)
    except ValueError:
        print("bad")
  2. What does this print?

    try:
        n = int("five")
        print(n + 1)
    except ValueError:
        print("bad")
    print("end")
  3. Why is except ValueError: better than a bare except:?

    • It only catches the error you expect, so real bugs still show up
    • It runs faster
    • A bare except is a syntax error
  4. What does this print?

    for text in ["4", "x", "6"]:
        try:
            print(int(text) * 10)
        except ValueError:
            print("skip")
  5. Which line has a mistake?

    try:
        print(10 / 0)
    except ValueError:
        print("Can't divide by zero")

Coding tasks

  1. Read one line. If it is a whole number, print it doubled. If not, print Not a number.

  2. Write safe_div(a, b) that returns a / b, or None when b is 0.

  3. Write to_int(text) that returns the text as a whole number, or 0 if it isn't one.