Module 09 · Lesson 03
Raising and Defining Your Own Exceptions
Make your functions report problems clearly: raise built-in exceptions with good messages, define your own exception classes, group them in a small family, and chain them with raise from.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Raise with a message
- Define your own
- Catch a family
- Watch a raise travel
Raise your own alarms
Your code can stop with a clear message too, using `raise`. You can even invent new kinds of error.
raise
raise ValueError("age must be 0 or more")stops right here with your message.Pick a type
ValueErrorfor a bad value,TypeErrorfor the wrong kind,KeyErrorfor a missing key.Your own class
class SoldOut(Exception): passmakes a brand new exception type.A family
Give related exceptions one parent class, then catch them all with one
except.
Custom errors everywhere
Big programs name their own problems, so the code that catches them knows exactly what happened.
- Online shops
SoldOutandCardDeclinedcan both belong to aCheckoutErrorfamily. - Games
NotEnoughCoinsstops a purchase with a message the player understands. - Booking apps
DateTakenexplains exactly why a booking failed. - LibrariesBig Python packages define their own exceptions so you can catch just theirs.
A raise with a helpful message
This line stops a function on purpose. Tap each part to see its job.
Part 1 of 3
raise:Stops this function now and sends the exception up to whoever called it.
Raise and define exceptions
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6raise
raise stops the function with your own message. The caller decides what to do about it.
Your turn: Also reject ages over 130 with a different message.
def set_age(age):
if age < 0:
raise ValueError(f"age must be 0 or more, got {age}")
return age
print(set_age(12))
try:
set_age(-3)
except ValueError as e:
print("Problem:", e)Press Run to see what it prints.Watch a raise travel
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- class NameTooShort(Exception):
- pass
- def sign_up(name):
- if len(name) < 3:
- raise NameTooShort(f"{name} has {len(name)} letters")
- return "hello " + name
- for name in ["Maya", "Al"]:
- try:
- print(sign_up(name))
- except NameTooShort as e:
- print("try again:", e)
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.A KeyError's message:
try:
raise KeyError("color")
except KeyError as e:
print(e)0 of 6 answered
Common custom exception 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
raise ValueError("clear message") # raise a built-in
class AppError(Exception): # your own base exception
pass
class NotFoundError(AppError): # a more specific one
pass
raise NotFoundError("no such user")
except NotFoundError as e: # precise
except AppError: # the whole family
raise AppError("unknown code") from err # translate, keep the causePress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Validating a sign-up form
Write a check that raises a clear exception for each kind of bad sign-up data, and report the problem for several attempts without stopping.
class SignupError(Exception):
pass
class UsernameError(SignupError):
pass
class PasswordError(SignupError):
pass
def check_signup(username, password):
if len(username) < 3:
raise UsernameError("username needs at least 3 characters")
if not username.isalnum():
raise UsernameError("username may only use letters and digits")
if len(password) < 8:
raise PasswordError("password needs at least 8 characters")
return "welcome " + username
attempts = [("al", "secret123"), ("ana!", "secret123"), ("ana", "short"), ("ana", "secret123")]
for username, password in attempts:
try:
print(check_signup(username, password))
except SignupError as error:
print(f"{type(error).__name__}: {error}")Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Catching the base class first
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
try:
raise OutOfStockError('no mugs')
except ShopError:
print('shop problem')
except OutOfStockError:
print('restock')Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Warehousing
An inventory service with its own errors
A warehouse's stock module is used by the website, the till and the delivery app. Each of those programs reacts differently to problems, so the module raises clear errors and leaves the reaction to them.
Why Python fits
The stock module never prints or decides; it only raises. This caller back-orders shortages and rejects unknown items, while another program could catch the base
StockErrorand show one general message.Pythonclass StockError(Exception): pass class UnknownItemError(StockError): pass class NotEnoughStockError(StockError): pass stock = {"mug": 4, "lamp": 0} def take(item, qty): if item not in stock: raise UnknownItemError(f"no item called {item!r}") if stock[item] < qty: raise NotEnoughStockError(f"{item}: wanted {qty}, have {stock[item]}") stock[item] -= qty return stock[item] orders = [("mug", 3), ("lamp", 1), ("rug", 1), ("mug", 2)] for item, qty in orders: try: left = take(item, qty) print(f"took {qty} {item}, {left} left") except NotEnoughStockError as error: print("back-order:", error) except UnknownItemError as error: print("rejected:", error)OutputPress 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.
Should I always make my own exception class?
Can my exception carry extra data, like the item name?
How many custom exceptions should a program have?
What is the difference between Exception and BaseException?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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 9 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.