Kodokon kodokon.com

Errors and exceptions: try, except, raise

Catch predictable failures with try/except/else/finally and raise your own exceptions to signal invalid data.

9 min · 3 questions

Open this lesson in Kodokon

A real program fails: missing file, invalid input, dropped network. Python signals these situations with exceptions, which interrupt execution and propagate up the call stack until a try/except catches them. The professional reflex: catch the most specific exception possible, as close as possible to where you know what to do.

PYTHON
def parse_age(text):
    try:
        return int(text)
    except ValueError:
        return None

print(parse_age("34"))      # 34
print(parse_age("thirty"))  # None
We catch ValueError precisely, not every error.

The full block has four branches. try contains the risky code, except handles the failure, else runs only if no exception was raised, and finally runs in every case - ideal for releasing a resource or logging. The point of else: keep the try minimal, so you can see at a glance which line can fail.

PYTHON
values = ["10", "abc", "25"]
total = 0

for value in values:
    try:
        number = int(value)
    except ValueError:
        print(f"Skip : {value}")
    else:
        total += number
    finally:
        print(f"Process : {value}")

print(total)  # 35
else runs only when there is no error; finally always runs.

Your functions can also raise their own exceptions with raise, as soon as a piece of received data is invalid: better to fail immediately with a clear message than to produce a wrong result. Define a dedicated class inheriting from Exception: the caller will be able to catch it specifically, without accidentally intercepting other errors.

PYTHON
class EmptyCartError(Exception):
    pass

def checkout(items):
    if not items:
        raise EmptyCartError("Empty cart.")
    return round(sum(items), 2)

try:
    print(checkout([]))
except EmptyCartError as error:
    print(f"Error : {error}")
A dedicated business exception makes the failure explicit and targeted.

Knowledge check

Make sure you remember the key points of this lesson.

  1. When does the else block of a try/except run?
    • Only if no exception was raised in the try
    • Only if an exception was caught
    • In every case, after the try
  2. In which cases does the finally block run?
    • Only if an exception was raised
    • Only if no exception was raised
    • In every case, exception or not
  3. Why avoid a bare except: that catches everything?
    • It hides real bugs and makes debugging very difficult
    • It is slower than a targeted except
    • It only works with standard-library exceptions