Lesson 31 of 34 · Errors & Pythonic Tools
Raising Custom Exceptions in Python
Catching exceptions is only half the story. Your own functions should raise exceptions when they can't do their job — that's how a function says "I refuse: this input makes no sense" instead of silently returning a wrong answer. And with custom exception classes, callers can tell exactly what went wrong and react to each problem precisely.
Raising an exception
Use raise with an exception object. Execution stops immediately and the exception travels up to the nearest matching except:
def set_volume(level):
if not 0 <= level <= 10:
raise ValueError(f"Volume must be between 0 and 10, got {level}")
return level
set_volume(11) # ValueError: Volume must be between 0 and 10, got 11
Pick the built-in exception whose meaning fits: ValueError for a bad value, TypeError for the wrong type, KeyError or LookupError for something missing. Write messages that help: say what was expected and what actually arrived.
Guard clauses
Checking for invalid input at the top of a function — and raising right away — keeps the "happy path" flat and readable:
def buy(gold, price):
if price < 0:
raise ValueError("Price cannot be negative")
if price > gold:
raise ValueError("Not enough gold")
return gold - price
Custom exception classes
A custom exception is simply a class that inherits from Exception. Even an empty one is useful, because callers can catch it specifically:
class QuestLockedError(Exception):
pass
def start_quest(level):
if level < 5:
raise QuestLockedError("Reach level 5 to start this quest")
return "Quest started!"
try:
start_quest(2)
except QuestLockedError as error:
print(error) # Reach level 5 to start this quest
By convention, exception names end in Error.
Exceptions that carry data
Give your exception an __init__ to store extra details for the code that catches it. Pass a message to super().__init__() so that printing the error still works:
class TooHeavyError(Exception):
def __init__(self, weight, limit):
super().__init__(f"{weight} kg exceeds the limit of {limit} kg")
self.weight = weight
self.limit = limit
try:
raise TooHeavyError(12, 10)
except TooHeavyError as error:
print(error) # 12 kg exceeds the limit of 10 kg
print(error.weight - error.limit) # 2
Exception hierarchies
Larger programs define a base exception and derive specific ones from it. Callers can then catch one specific problem — or all of them at once:
class GameError(Exception):
pass
class SaveFileError(GameError):
pass
class InvalidMoveError(GameError):
pass
# except GameError: catches both kinds
Re-raising and chaining
Inside an except block, a bare raise re-raises the current exception — useful after logging. To translate a low-level error into your own, use raise ... from ..., which keeps the original exception attached as the cause so the full story appears in the traceback:
def load_level(text):
try:
return int(text)
except ValueError as error:
raise GameError(f"Corrupt level value: {text!r}") from error
assert is not for validation
assert condition, "message" raises AssertionError when the condition is false. It's meant for internal sanity checks while developing, and Python can be run with assertions switched off. Validate user input with if and raise instead.
Common mistakes
- Raising a string:
raise "Oops"fails withTypeError: exceptions must derive from BaseException. - Raising the generic
Exception: callers can't catch your problem without catching everything else too. - Forgetting
super().__init__(message)in a custom exception, sostr(error)is empty or confusing. - Losing the original error: translate exceptions with
raise NewError(...) from error.
Assignment
Build a safe withdrawal for the Hollow's bank:
InsufficientFundsError— a custom exception that inherits fromException. Its__init__(self, balance, amount)storesbalanceandamountas attributes, and its message is"Cannot withdraw <amount>: balance is only <balance>".withdraw(balance, amount)returns the new balance,balance - amount. But:- if
amountis zero or negative, raiseValueErrorwith the message"Amount must be positive"; - if
amountis greater thanbalance, raiseInsufficientFundsError(balance, amount).
- if
withdraw(100, 30) # 70
withdraw(100, -5) # ValueError: Amount must be positive
withdraw(50, 80) # InsufficientFundsError: Cannot withdraw 80: balance is only 50Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Custom errors in other languages
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .