Skip to content
Kuza Ndoto Academy

Try, Except & Finally

Beginner → IntermediateChapter 7 · Page 38 of 564 min readUpdated 15 Nov 2026

A try/except block lets your program catch an exception and respond sensibly instead of crashing. It's how real programs survive bad input, missing files and network problems.

The basic try/except

Put the code that might fail inside try. If an exception of the named type happens, Python jumps straight to the matching except block, then carries on after it.

def to_number(text):
    try:
        return int(text)
    except ValueError:
        print(f"'{text}' is not a whole number")
        return None

print(to_number("42"))
print(to_number("forty"))
42 'forty' is not a whole number None

The classic use is asking the user for a number until they type a valid one:

while True:
    text = input("How old are you? ")
    try:
        age = int(text)
        break                  # only reached if int() worked
    except ValueError:
        print("Please type a whole number, e.g. 19.")

print(f"Next year you will be {age + 1}.")

A sample run, where the user first types a word:

How old are you? nineteen Please type a whole number, e.g. 19. How old are you? 19 Next year you will be 20.

Handling different exceptions

You can have several except blocks. Python uses the first one that matches.

prices = {"sugar": 180, "rice": 220}

def total_cost(item, quantity):
    try:
        return prices[item] * int(quantity)
    except KeyError:
        print(f"Sorry, we don't sell {item}.")
    except ValueError:
        print(f"'{quantity}' is not a valid quantity.")
    return 0

print(total_cost("rice", "3"))
print(total_cost("bread", "2"))
print(total_cost("sugar", "two"))
660 Sorry, we don't sell bread. 0 'two' is not a valid quantity. 0

To handle several types the same way, list them in a tuple: except (KeyError, ValueError):. To read the error message, add as and a name: except ValueError as error:.

else and finally

A full try statement has up to four parts:

BlockWhen it runs
tryAlways runs first
exceptOnly if a matching exception happened in try
elseOnly if try finished with no exception
finallyAlways, whether there was an error or not, even after return
try error raised? yes no excepthandle the error elsesuccess only finallyalways runs
Figure 1. If try raises an error that an except block matches, that block runs; if no error is raised, else runs. finally runs in every case, even when an unmatched error carries on up to the caller.
def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    except TypeError as error:
        print("Bad types:", error)
        return None
    else:
        print("Division worked")
        return result
    finally:
        print("safe_divide finished")

print(safe_divide(10, 4))
print(safe_divide(5, 0))
print(safe_divide(5, "2"))
Division worked safe_divide finished 2.5 Cannot divide by zero safe_divide finished None Bad types: unsupported operand type(s) for /: 'int' and 'str' safe_divide finished None

Look carefully at the order: finally runs before the function actually hands back its value, which is why "safe_divide finished" appears before each result is printed. Use else for code that should run only on success, which keeps the try block small. Use finally for clean-up that must always happen, such as closing a connection or saving a log.

Catching broadly, carefully

Sometimes, at the very top of a program, you want to catch anything unexpected, log it and exit politely. Use except Exception as error: for that, and keep it as the last except block.

def main():
    data = {"total": 1500}
    print(data["count"])        # oops: no such key

try:
    main()
except Exception as error:
    print(f"Something went wrong ({type(error).__name__}: {error})")
Something went wrong (KeyError: 'count')
Common mistake

A bare except: (with no exception type) catches everything, including typos that cause NameError and even Ctrl+C. Bugs then fail silently and become very hard to find. Always name the exceptions you expect, and use except Exception only as a last resort at the top level.

Common mistake

Putting twenty lines inside one try block makes it unclear which line you expected to fail, and may catch errors you didn't mean to hide. Keep the try block to the one or two lines that can actually raise the exception, and move the rest into else.

Ask forgiveness or look before you leap?

Python programmers often prefer "it's easier to ask forgiveness than permission" (EAFP): just try the operation and handle the exception. The alternative, "look before you leap" (LBYL), checks first.

stock = {"pens": 40, "books": 12}

# LBYL: check first
if "rulers" in stock:
    print(stock["rulers"])
else:
    print("No rulers recorded")

# EAFP: try, then handle
try:
    print(stock["rulers"])
except KeyError:
    print("No rulers recorded")

# Often simplest of all for dictionaries
print(stock.get("rulers", 0))
No rulers recorded No rulers recorded 0

Both styles are valid. EAFP shines when checking first is awkward or unreliable, for example with files, which could be deleted between your check and your open().

When the code that might fail also needs clean-up (like closing a file), a with statement is usually neater than finally. See Context Managers.

Key points

  • try runs risky code; except SomeError handles that error.
  • Use several except blocks, or a tuple, for different exception types.
  • else runs on success; finally always runs, even after return.
  • Name specific exceptions; avoid bare except:.
  • Next, learn to signal your own errors with raise.
Up next · Files & ErrorsRaising ExceptionsSignal problems in your own code.
→

Tip: use the ← and → keys to move between pages.