runtime
86 / 250
lesson 86 Exceptions & Validation · intermediate

Catch one specific error

`int("twelve")` stops a program with ValueError. `try` and `except ValueError` let you decide what a bad value means, without hiding any other mistake.

You'll be able to
  • Put only the line that can fail inside try, and handle its error in except ValueError:
  • Explain why naming the error type matters: other errors still stop the program
  • Parse a list of texts, keep the good values and count the rejected ones
The idea

A CSV of invoice lines delivers every value as text, and people type what they like: "12", " 6 ", "twelve", "". int("12") works. int("twelve") can't, so Python raises a ValueError, and an error nobody handles stops the program.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · One bad quantity stops everything
quantities = ["12", "6", "twelve", "24"]
for text in quantities:
    print(int(text))

try: marks lines that might fail. If one of them raises a ValueError, Python jumps straight to the matching except ValueError: block and then carries on after it; if nothing fails, the except block is skipped.

Always name the error. except ValueError: handles exactly the problem you expect (text that isn't a number). Every other error, such as a typo that raises NameError, still stops the program and shows you where. A bare except: would swallow those too, and the bug would hide behind your fallback value.

example-2.py · Skip what can't be read
quantities = ["12", " 6 ", "twelve", "", "24"]
total = 0
for text in quantities:
    try:
        total += int(text)
    except ValueError:
        print("skipped", repr(text))
print("total:", total)

Inside a function, the except block decides what a bad value means: here, None for "no usable price". The specific type also protects you: float(None) raises TypeError, not ValueError, so a missing value is not silently treated like a typo.

example-3.py · A price, or None
def to_price(text):
    try:
        return float(text)
    except ValueError:
        return None

for raw in ["6.95", "1,234.50", "  2.55", "N/A"]:
    print(repr(raw), "->", to_price(raw))

When to use it: when a failure is expected and you know what to do about it (skip the value, count it, use a default). Mistakes to avoid: wrapping many lines in one try, so you can't tell which one failed; a bare except:, which also hides real bugs; and catching an error you can't do anything useful about.

Review
  • try: runs code that may fail; except ValueError: handles that one error and carries on.
  • Name the error. Other errors still stop the program, which is how you find real bugs.
  • Keep try blocks small: one risky operation, one decision about what failure means.
  • Next: read the error itself, and handle different errors in different ways.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Catch one specific error — Exceptions & Validation · Runtime