Skip to content
ComputerCS
Start learning

Python Programming · Lesson 2.9.1.1

try / except / else / finally

Catch expected failures with try/except, react with else, clean up with finally, and raise your own errors for bad data.

01

Learning objectives

  • Wrap risky statements in try and handle a specific exception in except.
  • Explain why except ValueError is preferred over a bare except.
  • Use else (runs only on success) and finally (runs always) correctly.
  • Raise ValueError with a custom message to reject invalid data.
  • Write a validation loop that keeps asking until the input is valid.
02

Lesson notes

Some failures are not bugs but facts of life: users type 'abc' where a number belongs, a denominator turns out to be zero, a record is missing. Exception handling lets the program respond instead of dying. Wrap the risky statements in a try block; if the specified error occurs there, control jumps straight to the matching except clause and the program carries on from after the frame.

Catch specifically: except ValueError: for bad conversions, except ZeroDivisionError: for zero denominators. A bare except: catches everything — including the NameError caused by your own typo — and thereby hides real bugs, which is why the book and every style guide discourage it. One try block may list several except clauses, and Python runs the first one whose exception type matches.

Two optional clauses complete the frame. else runs only when the try block finished with no exception — the all-went-well branch. finally runs always, whether or not an error occurred and even while a value is being returned: it is the place for clean-up messages and bookkeeping. Remember the order — try, then except clauses, then else, then finally — a sequence MCQs love to shuffle.

You can raise errors yourself: raise ValueError('percentage must be 0-100'). This turns silent nonsense into a loud, describable failure that the caller's except can handle. The convention is simple — reuse built-in exception types, usually ValueError for bad values, and put a helpful message inside the brackets. Raising early is a service to whoever uses your function: bad data is stopped at the door with its name attached.

The validation loop ties it together: while True: ask, try to convert, break on success, and in except ValueError print a friendly rejection and loop again. The user then cannot crash the program no matter what they type. Board tip: long questions ask for exactly this pattern — practise writing it end to end, including the else clause that confirms the value only after a valid conversion.

03

Worked code examples

One try, many inputs

int('abc') raises ValueError inside the try, so the except prints the rejection and the loop continues — the program never dies.

for text in ["42", "abc", "17"]:
    try:
        n = int(text)
        print(n, "ok")
    except ValueError:
        print(text, "rejected")
Output
42 ok
abc rejected
17 ok

else runs on success, finally always runs

finally prints before each printed result because it runs while the function is returning; else carried the successful division and except carried the zero case.

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "undefined"
    else:
        return result
    finally:
        print("attempt finished")

print(safe_divide(9, 3))
print(safe_divide(9, 0))
Output
attempt finished
3.0
attempt finished
undefined

Raising and catching your own rule

150 is a valid int but breaks the range rule, so the function raises with its own message; the caller's except reports it and the loop moves on.

def parse_percentage(text):
    value = int(text)
    if value < 0 or value > 100:
        raise ValueError("percentage must be 0-100")
    return value

for entry in ["88", "150", "73"]:
    try:
        print(parse_percentage(entry), "accepted")
    except ValueError as err:
        print("Rejected:", err)
Output
88 accepted
Rejected: percentage must be 0-100
73 accepted
04

Key terminology

try block

The suite of risky statements whose exceptions you want to catch.

except clause

The handler for a named exception type, run only when that exception occurs.

else clause

The suite that runs only when the try block completes without any exception.

finally clause

The suite that runs on every path — success, handled error, even during return.

raise

The statement that triggers an exception yourself, usually with a message.

05

Common misconceptions

Common mistake

try/except repairs the failing statement so it can still succeed.

Correct understanding

The failed statement is skipped — handling decides what happens next; it does not make the failed operation succeed.

Common mistake

finally runs only when no exception occurred.

Correct understanding

finally runs on every path — success, handled error, even during a return — which is why it is used for clean-up.

Common mistake

A bare except is the safest because it catches everything.

Correct understanding

It also swallows typos and programming bugs like NameError, hiding them. Catch the specific exceptions you expect.

06

Check your understanding

1. In try/except/else/finally, when does the else suite run?

2. safe_divide has a finally clause and is called twice. How many times does its message print?

3. Why prefer except ValueError over a bare except?

NERDLYY · FEEDBACK

Help shape Nerdlyy

Your feedback goes directly to the team. We read every submission.

No reply needed — you can send feedback without sharing contact details.