Search code examples
pythonexceptionvalueerror

ValueError not being caught


I'm having some trouble capturing the ValueError exception.

  1. If I test an input with a string i.e. 'a' instead of providing an int number, then it throws a ValueError as expected. But then why does my exception not capture this and print "error, try again with an integer"?

I gave it 've' as I haven't used this variable yet. I didn't give 'e', as I've already used this for another exception.

  1. If I instead try except (TypeError,ValueError): then why does this also not work?

Note that this code is just for me to practice handling exceptions, the content itself is not meaningful.

while not correct_input:
    distance_travelled = float(input("enter distance travelled in km: ")) #input enters strings, so you must convert to the datatype you want
    monetary_value = float(input("amount paid to cover distance: "))
    price_per_litre = 1.59
    try:
        fuel_consumed = monetary_value/price_per_litre
        if monetary_value/price_per_litre < 0:
            raise Exception #I can raise my own custom exception here
    except Exception as e:
        print("too small, try again")
    except ValueError as ve: #Catch our exception, and handle it properly. Ensure specific exceptions at the top, general at the bottom
        print("error, try again with an integer")
    else: #Runs code if try doesn't raise an exception
        print(fuel_consumed)
        correct_input = True
    finally: #Regardless of error or not, what you wish for it to do. i.e. close a file, close database etc
        continue

Thanks


Solution

  • < 0 you ll only meet this condition when you ll enter negative values, please see if you want that or you want < 1. else the code is follwing.

    correct_input = False
    while not correct_input:
        try: # just check if you are getting integer/floating value here only
            distance_travelled = float(input("enter distance travelled in km: ")) #input enters strings, so you must convert to the datatype you want
            monetary_value = float(input("amount paid to cover distance: "))
        except:
            print('Only Integer and Floting point number')
        price_per_litre = 1.59
        try:
            fuel_consumed = monetary_value/price_per_litre
            if monetary_value/price_per_litre < 0: # I have a doubt if you really want 0 here. OR 1
                raise ValueError # raise value error when condition is met.
        except ValueError as ve:
            print('Too Small')
    
        else:
            print(fuel_consumed)
            correct_input = True
        finally:
            continue