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 LocationTooFarError that still inherits from the built-in Exception class.
  • 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 Exception class 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!
  • The __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>
  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: self, and supply.

Inside the method, store supply into the variable self.supply.


Define a __str__ method which returns, 'Available supply is only ' + str(self.supply).


Modify raise InventoryError by passing in supply to the exception’s constructor method.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?