Full answer
python
def parse_and_divide(text):
try:
n = int(text)
except ValueError:
print(" except: not a number")
else:
print(" else:", 100 / n)
finally:
print(" finally")
for value in ["10", "ten", "0"]:
print(value)
try:
parse_and_divide(value)
except ZeroDivisionError as e:
print(" caller caught:", e)
def early():
try:
return "from try"
finally:
print("finally before return")
print(early())Output:
text
10
else: 10.0
finally
ten
except: not a number
finally
0
finally
caller caught: division by zero
finally before return
from tryFor '10' the conversion succeeds, so else runs and then finally. For 'ten' the ValueError is handled by except, else is skipped and finally still runs. For zero, the division in else raises ZeroDivisionError, which is not caught by the except ValueError; finally runs anyway and the error propagates to the caller's handler.
The last example shows that finally runs even when the try block returns. A return inside finally would override that value and swallow exceptions, so it is best avoided; Python 3.14 starts warning about it.
Catch specific exceptions rather than bare except:, which also catches KeyboardInterrupt and SystemExit.
python
def parse_and_divide(text):
try:
n = int(text)
except ValueError:
print(" except: not a number")
else:
print(" else:", 100 / n)
finally:
print(" finally")
for value in ["10", "ten", "0"]:
print(value)
try:
parse_and_divide(value)
except ZeroDivisionError as e:
print(" caller caught:", e)
def early():
try:
return "from try"
finally:
print("finally before return")
print(early())Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- except handles named exceptions
- else runs only on success
- finally always runs
- Keep try blocks small
- Avoid bare except and return in finally
Common mistakes
- Putting all the code in try
- Catching every exception with a bare except
Follow-ups
- What does raise ... from ... do?
- How do exception groups and except* work?
Tips
- Trace each case step by step