How can I catch a raised exception and pass the lesson?

Hi! I was wondering why this code doesn’t work, anyone can help?

  def buy(self, color):    
    if self.stock[color] == 0:
      raise OutOfStock
      self.stock[color] = self.stock[color] - 1

Thanks in advance!

1 Like

Hey! I know this was written a while ago, and I’m not sure if this was what was happening on your end, but I wanted to mention…for others that might be like me specifically…

I wrote this exact code for the exercise and kept getting errors in the console. Then I realized that I was supposed to be getting an error…because we’re raising an error…haha.


I’ve written the exact same thing. Stock shouldn’t be able to be negative anyways, so checking for 0 is fine.
Also, we are not raising an exception from outside of the buy method, as the hint suggests. I don’t understand why this code is not valid.


Hi @tzyyyy97 :wave:


As referenced by @evvi33, the exercise is failing because of the exception. I also agree with @arlach, and I believe your code is correct. (I’ll show you another way to enhance the exception toward the end of this response. :wink: )

The solution would require us to not only raise the exception, but handle it appropriately. The first part of the hint tells us what we should do with the code:

We reject code that raises exceptions…

A good way to handle errors and reject code is to use a try-except block. We can see this used in the KitchenException example:

# User-defined exceptions for kitchen appliances.
class KitchenException(Exception):

class MicrowaveException(KitchenException):

class RefrigeratorException(KitchenException):

def get_food_from_fridge():
  if refrigerator.cooling == False:
    raise RefrigeratorException

def heat_food(food):
  if microwave.working == False:
    raise MicrowaveException

  food = get_food_from_fridge()
  food = heat_food(food)
except KitchenException:
  food = order_takeout()

If the KitchenException is raised, we declare food = order_takeout().


Move into a try-except block.

# This should raise OutOfStock:
except OutOfStock:
  print("This item is out of stock.")

Bonus Solution

Additionally, you can pass an argument* to the exception class and use it in your except block:

class CandleShop:
  # If color is out of stock, raise OutOfStock and pass a custom message.
  def buy(self, color):    
    if self.stock[color] == 0:
      raise OutOfStock("The {color} candles are out of stock.".format(color=color))
      self.stock[color] = self.stock[color] - 1

# This should raise OutOfStock:
except OutOfStock as e:
  # Print the custom message (e)

* See more on exception args:

I hope this helps. :slight_smile: