Watch Me Code 2: The Need For Exception Handling

This demonstrates the need for exception handling.


In [2]:
# this generates a run-time error when you enter a non-number

# for example enter "heavy" and you get a ValueError
weight = float(input("Enter product weight in Kg: "))


Enter product weight in Kg: heavy
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-b3784e942d08> in <module>()
      2 
      3 # for example enter "heavy" and you get a ValueError
----> 4 weight = float(input("Enter product weight in Kg: "))

ValueError: could not convert string to float: 'heavy'

In [3]:
# This example uses try..except to catch the ValueError
try:
    weight = float(input("Enter product weight in Kg: "))
    print ("Weight is:", weight)
except ValueError:
    print("You did not enter a number! ")


Enter product weight in Kg: fsdgjsdfg
You did not enter a number! 

In [ ]: