🛟 Errors & Exceptions, lesson 5 of 6
Raising & custom exceptions
Signal problems with raise, validate input and define your own errors.
12 min
2 exercises
1 quiz
0/3 solved
Getting Python ready… examples can run in a moment.
So far Python raised the errors. You can raise them too, with raise. It's how a function says "I can't work with this input" instead of silently returning a wrong value.
Refuse bad input
Your message appears in the traceback. Change 250 to 100 and the program finishes normally.
Why raise instead of print? A printed warning is easy to miss and the program keeps going with bad data. An exception makes the caller decide: handle it with try/except, or crash loudly.
Pick a fitting type: ValueError for bad values,
TypeError for wrong types.
Validate, then handle
One except handles both problems: the one int()
raises and the one you raise yourself.
Ask until the input is valid
One line per input() call
The pre-filled input answers "abc", then "42", then "7". Edit the input lines to try other values.
What does this print?
Validate a username
Make validate_username(name):
- raise
TypeErrorifnameis not a string - raise
ValueErrorif it's shorter than 3 or longer than 12 characters - raise
ValueErrorif it contains a space - otherwise return the name in lowercase
Custom exceptions. You can define your own exception types. Classes come in the next module; for now this two-line recipe is all you need:
class OutOfStockError(Exception):
pass
It inherits from Exception, so it works with
raise and except like any built-in. A clear name
documents the problem and lets callers catch exactly
your error and nothing else.
A custom exception
Add withdraw(10, 99) on its own line at the end
and run it: your custom name appears on the last line
of the traceback.
Out of stock!
- Define a custom exception
OutOfStockError. - In
buy(stock, item), raiseOutOfStockError(item)when the item's count is 0 or the item is missing. Otherwise decrease its count by 1 and return the new count.