LearnPy Hub
IntermediateIntermediateLesson 16 of 32

Exceptions

Watch the ideaCatching errors with try
try:
    n = int("abc")
    print("never printed")
except ValueError:
    print("Not a number!")
finally:
    print("Done")
try
except ValueError
finally

Python tries the risky code inside try.

1Level 1 · BasicsBasics

Things go wrong: a user types "abc" where you expected a number, a file is missing, someone divides by zero. When Python hits a problem it raises an exception, and if nobody handles it, the program stops with an error message. This lesson shows how to read those messages and handle errors gracefully.

Reading an error message

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(10 / n)
ZeroDivisionError: division by zero

Read it from the bottom: the last line names the error type and what happened, and the lines above show where (line 2). Error messages are your friends. They tell you exactly where to look.

Common exceptions

ExceptionTypical cause
ValueErrorint("abc"): right type, wrong value
TypeError"5" + 5: wrong type for the operation
ZeroDivisionErrordividing by zero
IndexErrorlist index out of range
KeyErrormissing dictionary key
NameErrormisspelled or undefined variable
FileNotFoundErroropening a file that doesn't exist

try and except

Put risky code in a try block, and say what to do if a particular error happens in except:

try:
    age = int(input("Age: "))
except ValueError:
    print("Please type a whole number.")

Catch specific exceptions. A bare except: also hides typos and real bugs.

else and finally

  • else: runs only if no exception happened.
  • finally: runs always, which is useful for clean-up such as closing a file.

Getting the message and raising your own

except ValueError as e: stores the error in e, so you can print its message. You can also raise exceptions yourself when your function gets bad input:

if amount < 0:
    raise ValueError("amount can't be negative")
Key points: read tracebacks from the bottom up; wrap risky code in try/except; catch specific exception types; else runs on success and finally always runs; raise signals a problem yourself.

See it in actiontry/except catches the bad value

When int("abc") fails, Python jumps to the except block and then carries on with the loop.

Step-by-step

Try it yourselfExample 1: Catching a ValueError

Change the input to a number and run again.

example_1.py
Output appears here
Fill in the blanks

Catch bad input

Fill the blanks so typing abc prints Not a number instead of crashing.

blanks.py
text = input()
:
    n = int(text)
    print(n * 2)
 ValueError:
    print("Not a number")

Example 2: Several kinds of error

Each except handles a different problem. Try changing the divisor or the index.

example_2.py
Output appears here
Fix the bug

Dividing by zero

This should print Can't divide by zero when b is 0, but it crashes because it catches the wrong error. Fix it.

buggy.py
Your turn

Safe division

Read two whole numbers (one per line) and print a ÷ b with //. If b is 0 print Error: zero; if either isn't a number print Error: number.

Example input10 3Expected output3

my_code.py

Example 3: else and finally

else runs only on success; finally runs either way.

example_3.py
Output appears here
Fill in the blanks

Always say goodbye

Fill the blank so Done is printed whether or not an error happened.

blanks.py
try:
    print(int("7") + 1)
except ValueError:
    print("Bad number")
:
    print("Done")

Example 4: Raising your own exception

The function refuses bad input, and the caller decides what to do about it.

example_4.py
Output appears here
Your turn

Raise your own error

Write set_age(age) that raises ValueError("Age can't be negative") for a negative age and otherwise returns it. Then try set_age(-3) and print the error message.

my_code.py

2Level 2 · IntermediateValidating input and raising errors

Retry until valid

Wrap int(input()) in a loop with try/except ValueError, so a typo asks again instead of crashing.

Raise the right built-in error

raise ValueError("need 100 Tk more") stops a function with a clear message. Pick the built-in type that fits (ValueError for a bad value, TypeError for the wrong kind of thing), so callers can catch exactly the problem they care about. After the Classes lesson you will be able to make your own error types.

Catch narrow, not wide

except Exception: also hides your own bugs (a typo in a variable name becomes a silent failure). Catch the specific errors you expect.

EAFP vs LBYL

Python style is often "easier to ask forgiveness than permission": try the action and handle the error, rather than checking every condition first.

See it in actionWhere the error jumps

Watch the arrow jump from the failing line straight into except, skipping the rest of try.

Step-by-step

Example 5: Ask again until the input is valid

The Input box has two bad answers before a good one.

example_5.py
Output appears here

Example 6: Raising an error for a bank account

withdraw() raises ValueError with a clear message; the caller catches only that, so other bugs would still show.

example_6.py
Output appears here

3Level 3 · AdvancedException chains, groups and clean-up

raise ... from ...

When you turn a low-level error into a clearer one, raise ValueError("bad port") from e keeps the original as the cause, so nothing is lost when debugging.

Exception hierarchy

Exceptions are classes in a tree: ZeroDivisionError is an ArithmeticError, which is an Exception. An except catches its class and all children, so order specific handlers before general ones.

ExceptionGroup and except*

Since Python 3.11, several errors can be raised together (common when validating a whole form or running tasks in parallel) and handled by type with except*.

Logging instead of print

logging.exception("...") inside an except records the message and the full traceback.

Example 7: Chaining with raise from

The clear message is what the user sees; __cause__ keeps the original error for whoever debugs it later.

example_7.py
Output appears here

Example 8: Collecting several errors at once

All problems in the form are reported together instead of one at a time.

example_8.py
Output appears here
Good practiceKeep the try block small, just the line that can fail, and catch the most specific exception you can. except Exception catches almost everything, so use it only at the very top of a program, and print the error so bugs aren't hidden.
Exercise · predict the output

What does this print?

try:
    x = int("3.5")
    print("A")
except ValueError:
    print("B")
finally:
    print("C")
Quick quiz · 5 questions
1. Which exception does int("hello") raise?
2. When does a finally block run?
3. Where do you look first in a traceback?
4. What does raise ValueError("bad") do?
5. Which error does [1, 2, 3][5] raise?
Ready to practice exceptions?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Exceptions · LearnPy Hub