Skip to contentSkip to navigation

Module 09 · Lesson 02

Handling Exceptions with try and except

Keep a program running when something goes wrong: catch specific exceptions with try and except, read the error with as, and use else, finally and raise in the right places.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • try and except
  • Handle each problem
  • else and finally
  • Watch Python jump to except

Plan for problems

`try` runs code that might fail. `except` says what to do if a particular problem happens.

  • try

    Put the line that might fail inside try:.

  • except

    except ValueError: runs only for that problem. Others still stop the program.

  • as

    except ValueError as e: keeps the exception so you can print its message.

  • else and finally

    else runs when nothing failed. finally runs every time.

Handling problems everywhere

Good apps expect things to go wrong and recover politely.

  • Sign-up formsAsk again when the age box gets letters instead of a number.
  • Game menusA wrong key press shows a hint instead of crashing the game.
  • DownloadsIf a download fails, try again a few times before giving up.
  • CalculatorsShow "cannot divide by zero" instead of a traceback.

The except line

This line handles one kind of problem. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

except:Runs only if the code in try raised a matching exception.

Catch problems before they crash

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Catch one

If a line in try fails with that exception, Python jumps to except instead of stopping.

Your turn: Change text to "12". Which lines run now?

Python
text = "twelve"
try:
    age = int(text)
    print("Next year:", age + 1)
except ValueError:
    print("Please type digits, like 12")
print("The program keeps going")
Output
Press Run to see what it prints.

Watch Python jump to except

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. def safe_divide(a, b):
  2. try:
  3. return a / b
  4. except ZeroDivisionError:
  5. return None
  6. print(safe_divide(9, 3))
  7. print(safe_divide(9, 0))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Which except block runs?

try:
    print([1, 2][9])
except KeyError:
    print("key")
except IndexError:
    print("index")

0 of 6 answered

Common try/except misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Catching an exception

Put the code that might fail inside a try block, and say what to do if it fails in an except block:

Try it 1: edit me, then Run
text = "ten"
try:
    number = int(text)
    print("Got", number)
except ValueError:
    print("Please enter digits, such as 10.")
print("Carrying on")
Output
Press Run to see what it prints.

Python runs the try block line by line. If a line raises a ValueError, the rest of the try block is skipped and the matching except block runs instead. Afterwards the program continues after the whole statement, so Carrying on is printed either way. If no exception happens, the except block is skipped entirely.

If the exception that happens is not the one named, for example a KeyError when you only catch ValueError, the except does not match. The exception carries on outward as if there were no try at all, and stops the program with a traceback unless something further out handles it.

Be specific

Always name the exception you expect. A bare except: or a broad except Exception: also catches the mistakes you did not expect: a misspelled variable name, a wrong argument, a bug in a function you called. The program then carries on with nonsense and the real cause is hidden. Catch the narrowest exception that describes the situation, and keep the try block short, ideally just the line that can fail.

Several exceptions

A try can have several except blocks; the first one that matches runs:

Try it 2: edit me, then Run
def safe_divide(a_text, b_text):
    try:
        return int(a_text) / int(b_text)
    except ValueError:
        return "not a number"
    except ZeroDivisionError:
        return "cannot divide by zero"

print(safe_divide("8", "2"))    # 4.0
print(safe_divide("8", "x"))    # not a number
print(safe_divide("8", "0"))    # cannot divide by zero
Output
Press Run to see what it prints.

To handle several exceptions the same way, list them in a tuple: except (ValueError, TypeError):. Because exceptions form a family tree, except LookupError: catches both KeyError and IndexError, and except OSError: covers FileNotFoundError and other file problems.

Reading the error with as

except ValueError as error: gives the exception object a name, so you can show or record its message:

Try it 3: edit me, then Run
try:
    int("4.5")
except ValueError as error:
    print("Problem:", error)    # Problem: invalid literal for int() with base 10: '4.5'
Output
Press Run to see what it prints.

str(error) is the message; type(error).__name__ is the exception's name. The name after as only exists inside that except block.

else and finally

Two optional blocks complete the statement:

Try it 4: edit me, then Run
try:
    value = int("42")
except ValueError:
    print("bad number")
else:
    print("converted", value)      # runs only if no exception happened
finally:
    print("check finished")        # always runs
Output
Press Run to see what it prints.

else holds the code that should run only when the try succeeded. Putting it in else instead of at the end of try keeps the try short, so an exception raised by that follow-up code is not mistaken for the one you meant to catch.

finally runs no matter what: after success, after a handled exception, and even when an unhandled exception is on its way out or a return leaves the function. It is for clean-up that must always happen, such as closing a connection or printing a summary. For files, with already does this clean-up for you.

Trying again

A common pattern combines try with a loop that repeats until it gets good data. In the browser the answers would come from input(); here they come from a list:

Try it 5: edit me, then Run
answers = ["", "twelve", "12"]
for answer in answers:
    try:
        age = int(answer)
        break
    except ValueError:
        print(f"{answer!r} is not a whole number, try again")
print("Age:", age)
Output
Press Run to see what it prints.

break leaves the loop as soon as a conversion works.

Ask permission or forgiveness?

The previous lesson checked before acting, for example if key in data:. Python programmers also often write the opposite style: just try it, and handle the failure. Both are fine. Trying first is better when the check would be complicated or repeat the work, such as deciding whether a string is a valid number including decimals and minus signs; float(text) inside try answers that perfectly. It is also the only safe choice when the situation can change between checking and acting, as with files that another program might delete. Checking first reads better when the failure is ordinary and cheap to test, such as an empty list.

Raising again

Sometimes you want to note a problem and still let it stop the program. A plain raise inside an except block re-raises the same exception:

Try it 6: edit me, then Run
try:
    value = {"a": 1}["b"]
except KeyError:
    print("lookup failed, giving up")
    raise
Output
Press Run to see what it prints.

You can also raise an exception yourself with raise ValueError("age cannot be negative"). The next lesson builds on that to create exceptions of your own.

Syntax

The general shape of the statements in this lesson.

syntax.py
try:
    risky()
except ValueError:                 # one specific exception
    ...
except (KeyError, IndexError) as e:   # several, with the object
    print(e)
else:
    ...                            # only when try succeeded
finally:
    ...                            # always
raise                              # re-raise inside except
raise ValueError("message")        # raise your own
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Reading numbers from messy text

Beginner

A file of temperature readings contains some broken lines. Convert what can be converted, count the bad lines and print the average of the good ones.

Python
from pathlib import Path

Path("temps.txt").write_text("21.5\n19\nerror\n22.0\n\n-3.5\n", encoding="utf-8")

readings = []
bad = 0
for line in Path("temps.txt").read_text(encoding="utf-8").splitlines():
    try:
        readings.append(float(line))
    except ValueError:
        bad += 1

print("Good:", readings)
print("Bad lines:", bad)
print("Average:", round(sum(readings) / len(readings), 2))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

float already understands decimals and minus signs, so trying it is simpler than writing checks for every format. The word error and the empty line both raise ValueError and are counted instead of stopping the loop.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

A bare except that hides bugs

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
try:
    total = sum(pricse)
except:
    total = 0
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

total is silently 0; the NameError from the typo pricse is never seen

Write this instead

try:
    total = sum(prices)
except TypeError:
    total = 0

Why it happens

A bare except catches every exception, including the ones caused by mistakes in your own code.

In the real world

Where this shows up in software people use every day.

  1. Processing payments without stopping the batch

    Payments

    A billing job charges a list of customers each night. One broken record must not stop everyone else from being billed, but every failure must be reported for a person to check.

    Why Python fits

    Each customer is handled in its own try, so a failure affects only that record. Two specific excepts give precise reasons, and the else records only successful conversions. The finally block counts every customer, charged or not, the way a real system would write one audit line per record.

    Python
    customers = [
        {"id": "c1", "amount": "19.99"},
        {"id": "c2", "amount": "free"},
        {"id": "c3"},
        {"id": "c4", "amount": "5"},
    ]
    
    charged, failed = [], []
    checked = 0
    for customer in customers:
        try:
            amount = float(customer["amount"])
        except KeyError:
            failed.append((customer["id"], "no amount"))
        except ValueError:
            failed.append((customer["id"], f"bad amount {customer['amount']!r}"))
        else:
            charged.append(amount)
        finally:
            checked += 1
    
    print(f"Checked {checked}, charged {len(charged)}, total {sum(charged):.2f}")
    for cid, reason in failed:
        print("Check", cid, "-", reason)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Does try make my program slower?

Hardly at all when no exception happens. Raising and catching costs a little more, but far less than you would notice for user input or file problems.

Can I catch an exception from a function I called?

Yes. An exception travels up through every function call until some try handles it, so a try around the call catches errors raised deep inside.

Should every line be inside a try?

No. Only wrap code where you expect a specific, recoverable problem and know what to do about it. Let real bugs crash, so you see and fix them.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 12 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.