Definition
What should a calculator do when someone divides by zero?
Exception handling lets a program respond to an error instead of crashing. Code that might fail goes in a try block; except blocks handle specific error types; else runs if no error happened; and finally always runs, error or not, often to clean up.
In simple words
try is 'attempt this'. except ZeroDivisionError is 'if it fails this way, do this instead'. A good program tells the user what went wrong in plain words and keeps going, instead of showing a scary traceback and stopping.
Why it matters
Real data is messy and real users make mistakes. Programs that read files, call web APIs or talk to LLMs must handle failures such as missing files, bad numbers and network errors, or they break at the worst moment.
How it works
try:
risky step
except ValueError:
handle bad input
except ZeroDivisionError:
handle division by zero
else:
runs only if nothing failed
finally:
always runsIn code
A calculator that never crashes: each bad case gets a clear message.
def divide(a_text, b_text):
try:
a = float(a_text)
b = float(b_text)
result = a / b
except ValueError:
return "Please type numbers only"
except ZeroDivisionError:
return "Can't divide by zero"
else:
return f"{a} / {b} = {result:.2f}"
finally:
print(" (checked", a_text, "and", b_text + ")")
for pair in [("10", "4"), ("10", "0"), ("ten", "2")]:
print(divide(*pair))Output
(checked 10 and 4) 10.0 / 4.0 = 2.50 (checked 10 and 0) Can't divide by zero (checked ten and 2) Please type numbers only
Try it yourself
Which block runs, and when?
For divide("10", "4"), which succeeds, put the blocks in the order they run.
- 1The function returns the message
- 2finally: print the 'checked' note
- 3else: build the result message
- 4try: convert both and divide
Common mistakes
- Catching every error with a bare except.
- Putting too much code in try, so you can't tell which line failed.
- Silently ignoring errors with pass. At least report what happened.
Check yourself
Summary
- try runs risky code; except handles specific errors.
- else runs on success; finally always runs.
- Catch specific errors and give users clear messages.
Finished reading?
Sources: Python docs: Handling Exceptions