Lesson 2 of 5 · Errors and Files · 2 min read · Updated
Raising your own errors
Refusing bad input loudly, and defining an error type of your own.
Your own functions can raise exceptions too. When a function is handed something it cannot sensibly work with, raising an error is better than quietly returning a wrong answer.
def set_marks(marks):
if not 0 <= marks <= 100:
raise ValueError(f"marks must be 0 to 100, got {marks}")
return marks
for m in [85, 120]:
try:
print("Saved", set_marks(m))
except ValueError as e:
print("Error:", e)
Saved 85
Error: marks must be 0 to 100, got 120
Choose the built-in exception that fits the problem and write a message that says what was wrong and what was expected. Whoever reads the traceback — often you — will know exactly what to fix.
An error type of your own
class InsufficientBalance(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalance(f"need {amount - balance} more")
return balance - amount
try:
withdraw(500, 800)
except InsufficientBalance as e:
print("Declined:", e)
Declined: need 300 more
Two lines define a new exception type. Callers can then catch exactly this problem and nothing else. The class keyword is covered properly in the Classes topic; for now, this pattern is all you need.
Note
Inside an except block, a bare raise re-raises the same exception. Use it when you want to note that something failed — print a message, say — but still let the error travel on to whoever can handle it.
A function receives a negative age. What is the best response?
Try this now
- Write
parse_percentage(text)that converts "45%" to 45 and raises ValueError for anything outside 0 to 100. - Define an
OutOfStockexception and raise it from a function that sells items from a stock dictionary.
Create a free account to save your progress, or sign in.