We’ve just seen how defining a simple exception class can provide a more specific and useful error to users. Defining a simple class is just the first step to creating better exceptions in our programs. Python does not stop us from customizing our custom exception classes even further.
Let’s say we wanted to expand our
LocationTooFarError exception from earlier to also provide a custom error message. Here is what the custom class might look like:
class LocationTooFarError(Exception): def __init__(self, distance): self.distance = distance def __str__(self): return 'Location is not within 10 km: ' + str(self.distance)
Let’s break this down:
- Our class definition doesn’t look much different from before. We have a class named
LocationTooFarErrorthat still inherits from the built-in
- We have added a constructor that is going to take in a distance argument when we instantiate our exception class. Here, we have overridden the constructor of the
Exceptionclass to accept our own custom argument of
distance. The reason for taking in a distance is to use it in our
__str__method that will return a custom error message when the exception is hit!
__str__method provides our exception a custom message by returning a string with the distance property from the constructor.
If we now ran it using our script from earlier:
def schedule_delivery(distance_from_store): if distance_from_store > 10: raise LocationTooFarError(distance_from_store) else: print('Scheduling the delivery...')
We would see our expanded custom exception in action:
Traceback (most recent call last): File "inventory.py", line 14, in <module> schedule_delivery(20) File "inventory.py", line 11, in schedule_delivery raise LocationTooFarError(distance_from_store) __main__.LocationTooFarError: Location is not within 10 km: 20
Let’s practice customizing our exceptions even further!
Let’s customize the
InventoryError from our previous exercise to return a custom error message. Inside the class, replace the
pass statement with an
__init__ method which takes two arguments:
Inside the method, store
supply into the variable
__str__ method which returns,
'Available supply is only ' + str(self.supply).
raise InventoryError by passing in
supply to the exception’s constructor method.