Encountering exceptions isn’t always an accident. We can throw an exception at any time by using the
raise keyword, even when Python would not normally throw it.
We might want to raise an exception anytime we think a mistake has or will occur in our program. This lets us stop program execution immediately and provide a useful error message instead of allowing mistakes to occur that may be difficult to diagnose at a later point.
One way to use the
raise keyword is by pairing it with a specific exception class name. We can either call the class by itself or call a constructor and provide a specific error message. So for example we could do:
raise NameError # or raise NameError('Custom Message')
When only the class name is provided (as in the first example), Python calls the constructor method for us without any arguments (and thus no custom message will come up).
For a more concrete example, let’s examine raising a
TypeError for a function that checks if an employee tries to open the cash register but does not have the correct access:
def open_register(employee_status): if employee_status == 'Authorized': print('Successfully opened cash register') else: # Alternatives: raise TypeError() or TypeError('Message') raise TypeError
When an employee_status is not
'Authorized', the function
open_register() will throw a
TypeError and stop program execution.
Alternatively, when no built-in exception makes sense for the type of error our program might experience, it might be better to use a generic exception with a specific message. This is where we can use the base
Exception class and provide a single argument that serves as the error message. Let’s modify the previous example, this time raising an
Exception object with a message:
def open_register(employee_status): if employee_status == 'Authorized': print('Successfully opened cash register') else: raise Exception('Employee does not have access!')
As a general rule of thumb, use an exception that provides the best explanation for the expected error for both the user and anyone that will read the code.
Later in this lesson, we’ll explore how to customize our exceptions further by creating user-defined exceptions. For now, let’s practice using the
Instrument World has a program that attempts to print the price of several instruments. Take some time to examine the program and then run the code and observe the output!
What do we expect to happen?
We hit a
'Piano' is not a key in the
Let’s provide a custom message by raising the exception ourselves. To accomplish this goal we will use a simple conditional.
First, inside of
print_instrument_price, add an
if statement that checks whether or not the
instrument parameter is found in
instrument_catalog. If it is, use the provided pre-written print statement to print the price.
Finally, let’s add an
else block where we will print our custom KeyError exception if the key does not exist. Inside, it should raise a
KeyError with the message
instrument + ' is not found in instrument catalog!'.