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:
- Python starts the
tryblock:int("abc")raises a ValueError. - The rest of the try block is skipped.
except ValueError:matches, so its block runs: "That's not a number".- 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")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 givesSyntaxError: 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
What does this print?
try: n = int("5") print(n + 1) except ValueError: print("bad")What does this print?
try: n = int("five") print(n + 1) except ValueError: print("bad") print("end")Why is
except ValueError:better than a bareexcept:?- It only catches the error you expect, so real bugs still show up
- It runs faster
- A bare except is a syntax error
What does this print?
for text in ["4", "x", "6"]: try: print(int(text) * 10) except ValueError: print("skip")Which line has a mistake?
try: print(10 / 0) except ValueError: print("Can't divide by zero")
Coding tasks
Read one line. If it is a whole number, print it doubled. If not, print
Not a number.Write
safe_div(a, b)that returnsa / b, orNonewhen b is 0.Write
to_int(text)that returns the text as a whole number, or 0 if it isn't one.