Python Errors and Exceptions: How to Use try, except, else and finally
P8.4 Python try except else finally Explained
Why. Sometimes you want code that runs only on success, and code that runs always — like closing a connection or logging.
What.
else:— runs only if no error happened.finally:— runs always, error or not.- You can have several
exceptblocks for different errors.
How.
Use all four parts
- try: the risky work.
- except: handle the error.
- else: what to do on success.
- finally: clean-up that must always happen.
Worked example A — Several except blocks.
Step 1 — What we do. We read a price from a product record that may be broken.
Step 2 — Type and run this code.
def get_price(rec):
try:
return float(rec["price"])
except KeyError:
return "no price field"
except ValueError:
return "price is not a number"
print(get_price({"price": "19.99"}))
print(get_price({"name": "Pen"}))
print(get_price({"price": "free"}))
Step 3 — Output you should see.
19.99
no price field
price is not a number
Step 4 — What it means. Each error type gets its own clear message.
Worked example B — else and finally.
Step 1 — What we do. A logistics job processes a batch and always logs at the end.
Step 2 — Type and run this code.
def process(qty):
try:
per_box = 100 / qty
except ZeroDivisionError:
print("Error: quantity is zero")
else:
print("Per box:", per_box)
finally:
print("Batch logged")
process(4)
process(0)
Step 3 — Output you should see.
Per box: 25.0
Batch logged
Error: quantity is zero
Batch logged
Step 4 — What it means. On success, else runs. On error, except runs. finally runs both times.
Ravindra Bagale's Tip
Use finally (or the with statement you will see in the files chapter) to close files and database connections.
Ravindra Bagale's Tip – मराठी
Files आणि database connections बंद करायला finally (किंवा files chapter मधला with) वापरा.
Ravindra Bagale's Tip – हिंदी
Files और database connections बंद करने के लिए finally (या files chapter वाला with) इस्तेमाल करो.