Ravindra BagaleCourses & study guides मराठी Track your progress

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

  1. Put the risky line inside try:.
  2. Write except with the error type.
  3. Decide what to do: default value, skip, or message.
1. Run the code in try2. No error? → continue after except3. Error? → jump to except4. Handle it and continue
try / except path (read from top to bottom)

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.