Several excepts, else and finally
🌍 In real life. A hospital's emergency desk has a different plan for each kind of problem: a cut goes to one room, a fever to another, and anything unusual to the senior doctor. Whatever happens, the patient's visit is written in the log at the end. And if nothing was wrong at all, the patient simply gets a "you're fine" note.
A try statement can have that same set of plans: several except blocks, an else, and a finally.
The idea in one sentence: Python checks the except blocks from the top and runs the first one that matches; else runs only when the try had no error, and finally runs always.
Its words:
- several excepts: one
exceptper kind of error, checked in order as e: gives you the error itself, so you can print its message- error family:
except ArithmeticErroralso catches a ZeroDivisionError, which is a kind of it;except Exceptioncatches almost anything else:andfinally:: "no error happened" and "always, at the end"
Step by step, for 100 // int(text) when text is "0":
int("0")works, but100 // 0raises a ZeroDivisionError.except ValueError:doesn't match, so Python checks the next one.except ZeroDivisionError as e:matches: it runs, and prints the message.
for text in ["8", "zero", "0"]:
try:
print(100 // int(text))
except ValueError:
print(text, "is not a number")
except ZeroDivisionError as e:
print("Problem:", e)Two more optional blocks: else runs only if the try block had no error, and finally runs always, error or not. finally is the place for clean-up, like saying goodbye or closing something.
for text in ["7", "seven"]:
try:
n = int(text)
except ValueError:
print(text, "failed")
else:
print(text, "worked:", n)
finally:
print("done with", text)Why else and finally? else keeps the try block short: only the risky line goes in the try, and what to do when it worked goes in else, where its own errors won't be caught by mistake. finally is for clean-up that must happen no matter what; it even runs when the try block returns.
Mistakes and edge cases.
- A broad except first.
except Exception:aboveexcept ZeroDivisionError:catches everything, so the specific block never runs. Put specific ones first. - Using the as name later. The
efromexcept ... as eis removed when the except block ends. - Expecting finally to stop the error. finally runs, and then an unmatched error keeps going (Lesson 18.4).
- else on a try that failed. It's skipped; that's the point of it.
Quiz
What does this print?
try: print([1, 2][5]) except ValueError: print("A") except IndexError: print("B")What does this print?
try: n = int("3") except ValueError: print("bad") else: print("good", n) finally: print("end")What does this print?
try: print(5 / 0) except Exception as e: print("Caught:", e)When does a finally block run?
- Always, whether there was an error or not
- Only when there was an error
- Only when there was no error
Which line has a mistake?
try: n = int("x") except Exception: print("something went wrong") except ValueError: print("not a number")
Coding tasks
Write
safe_index(items, i)that returnsitems[i], orNoneif there is no position i.Read two lines, a and b, and print
a // b. If either isn't a whole number, printNumbers only. If b is 0, printCan't divide by zero.