Raise vs try:except >>> Inheritance 2/9 exercise


#1

Hi
Can somebody explain to me if there is a difference between these approaches and why one passes the exercise and the other doesn’t please. I’m confused lol
It’s about the candle.buy() method. In my understanding both should raise an exception.

This passes :

# Define your exception up here:
class OutOfStock(Exception):
  pass

# Update the class below to raise OutOfStock
class CandleShop:
  name = "Here's a Hot Tip: Buy Drip Candles"
  def __init__(self, stock):
    self.stock = stock
    
  def buy(self, color):
    if self.stock[color] < 1:
      raise OutOfStock
    self.stock[color] = self.stock[color] - 1

candle_shop = CandleShop({'blue': 6, 'red': 2, 'green': 0})
candle_shop.buy('blue')

# This should raise OutOfStock:
# candle_shop.buy('green')

And this doesn’t :

# Define your exception up here:
class OutOfStock(Exception):
  pass

# Update the class below to raise OutOfStock
class CandleShop:
  name = "Here's a Hot Tip: Buy Drip Candles"
  def __init__(self, stock):
    self.stock = stock
    
  def buy(self, color):
    try:
      self.stock[color] = self.stock[color] - 1
    except OutOfStock:
      pass

candle_shop = CandleShop({'blue': 6, 'red': 2, 'green': 0})
candle_shop.buy('blue')

# This should raise OutOfStock:
# candle_shop.buy('green')

#2

Hi @kedlaw,

In the second version of the buy method, you have not informed the interpreter that there is any problem with subtracting 1 from self.stock[color] when its value is less than 1, so an OutOfStock Exception does not get raised. You need to communicate to the interpreter that this is not allowed under that condition …

      self.stock[color] = self.stock[color] - 1

In the first version of the method, you essentially informed the system that under this condition

    if self.stock[color] < 1:

… it should …

      raise OutOfStock

… instead of proceeding with the purchase.

Edited on November 26, 2018 to add the following …

To see how it works, try this at the end of your code …

# Try to buy a blue candle
try:
    candle_shop.buy('blue')
    print("Enjoy your blue candle!")
except OutOfStock:
    print("No blue candles available!")
    
# Try to buy a green candle
try:
    candle_shop.buy('green')
    print("Enjoy your green candle!")
except OutOfStock:
    print("No green candles available!")

#3

Ok , I understand. Thanks a lot.
Yes value less than 1 in not an error in it’s self. The try: tries and succeeds :smile:

Much appreciated.