Python try, except, else and finally Explained
try except else: Run Code Only When It Worked
The else block of a try runs only when the try block had no error. It's the place for the code that should run after the risky part succeeded.
try:
age = int(input())
except ValueError:
print("Please type a whole number.")
else:
print("Saved! Next year you will be", age + 1)Saved! Next year you will be 16
Type fifteen in the Input box and run it again: now only the except block runs.
Think of it like an exam. If you fail, you get the "try again" letter (except). If you pass, and only then, you get the certificate (else).
The rules
elsecomes after all theexceptblocks.- It runs only when the
tryblock finished with no error. - It needs at least one
exceptbefore it. - Exactly one of them runs: an
exceptblock, or theelseblock.
Why not put it all in try?
Because a big try can catch errors you didn't mean to catch.
Avoid: a big try
try:
qty = int(input())
price = int("12.5")
print("Total:", qty * price)
except ValueError:
print("Please type a whole number.")Please type a whole number.
The user typed 3, a perfect whole number! The real bug is int("12.5") on line 3: it should be float(). But the except caught that ValueError too, and blamed the user.
Good: only the risky line in try
try:
qty = int(input())
except ValueError:
print("Please type a whole number.")
else:
price = int("12.5")
print("Total:", qty * price)ValueError: invalid literal for int() with base 10: '12.5'
Now the bug shows itself with the right line, and you can fix it with float(). The except only covers the line that reads the input.
else runs only when the try block had no error. Keep try small, and put the next steps in else.