FAQ: Learn Python: Inheritance and Polymorphism - Exceptions


#1

This community-built FAQ covers the “Exceptions” exercise from the lesson “Learn Python: Inheritance and Polymorphism”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise Exceptions

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

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

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

Thanks in advance!


#3

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.


#4

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.


#5

Hi @tzyyyy97 :wave:

Explainer

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
  ...

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

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


Solution

Move CandleShop.buy() into a try-except block.

# This should raise OutOfStock:
try:
  candle_shop.buy('green')
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))
    else:
      self.stock[color] = self.stock[color] - 1

# This should raise OutOfStock:
try:
  candle_shop.buy('green')
except OutOfStock as e:
  # Print the custom message (e)
  print(e)

* See more on exception args: https://docs.python.org/3.6/library/exceptions.html#BaseException.args


I hope this helps. :slight_smile: