Your own exceptions
raise, input validation and your own error classes.
Exceptions can be raised as well as caught. If a function receives data it cannot work with, it is better to say so straight away than to return a strange result:
def set_age(age):
if age < 0:
raise ValueError("age must not be negative")
return age
raise stops the function, and the error travels up the chain of calls until something catches it. The message in an error is written for whoever will read it. It should make clear what is wrong with the value.
Check input at the boundary: where data comes from the user, from a file or from the network. Inside the program, after such a check, you can work without worry. The "check and leave early" pattern reads more easily than deeply nested ifs.
For errors of your own domain you declare your own class:
class PaymentError(Exception):
pass
It is caught separately from system errors: except PaymentError:. Error classes form a hierarchy. For example, KeyError and IndexError are subclasses of LookupError, and except LookupError catches both.
Inside except you can re-raise the error with a bare raise if you have only logged it and do not know what to do next. Or you can raise your own error with a clear message. Do not hide errors by turning them into None or an empty string for no reason: the calling code will never find out that something went wrong.
Practice
The parent class
What does the program print?
try: {}["x"] except LookupError: print("caught")Good habits
Mark the good practices for working with errors.
- Raising ValueError with a clear message on bad input
- Writing except: pass so the program does not crash
- Catching a specific type of error
- Returning None instead of any error with no explanation
Parsing an age
Write a function parse_age(text) that turns a string into an integer and returns it. If the string is not a number, or the age is below 0 or above 150, the function raises ValueError.