Python Errors and Exceptions: How to Use try, except, else and finally
P8.3 How to Use try and except in Python
Why. In a file of 10,000 rows, one bad row should not stop the whole job. try/except lets you handle it and continue.
What. Code inside try: runs normally. If an error happens, Python jumps to except: instead of crashing.
How.
Handle an error
- Put the risky line inside
try:. - Write
exceptwith the error type. - Decide what to do: default value, skip, or message.
Worked example A — Safe division.
Step 1 — What we do. Average order value, safe for days with zero orders.
Step 2 — Type and run this code.
revenue = 0
orders = 0
try:
aov = revenue / orders
except ZeroDivisionError:
aov = 0
print(aov)
Step 3 — Output you should see.
0
Step 4 — What it means. Instead of crashing, we set 0 and move on.
Worked example B — Convert many values, skip bad ones.
Step 1 — What we do. Amounts from a messy export of a shop in Athens.
Step 2 — Type and run this code.
raw = ["120.5", "abc", "99", "", "45.25"]
good = []
bad = 0
for r in raw:
try:
good.append(float(r))
except ValueError:
bad += 1
print(good)
print("Bad rows:", bad)
Step 3 — Output you should see.
[120.5, 99.0, 45.25]
Bad rows: 2
Step 4 — What it means. Good rows are kept, bad rows counted. Always report how many you skipped.
Python next to other languages — handle an error. You do not need to learn these other languages. This only shows why Python is easier to read.
| Language | Code |
|---|---|
| Python | try: ... except ValueError: ... |
| Java | try { ... } catch (NumberFormatException e) { ... } |
| JavaScript | try { ... } catch (e) { ... } |
| Go | v, err := strconv.ParseFloat(s, 64); if err != nil { ... } |
Ravindra Bagale's Tip
Never write a bare except: that hides all errors. Catch the specific error you expect, like ValueError.
Ravindra Bagale's Tip – मराठी
सगळ्या errors लपवणारा नुसता except: कधीच लिहू नका. अपेक्षित असलेली विशिष्ट error पकडा, उदा. ValueError.
Ravindra Bagale's Tip – हिंदी
सारे errors छिपाने वाला खाली except: कभी मत लिखो. जो error अपेक्षित है वही पकड़ो, जैसे ValueError.