Search code examples
pythonexcept

Python: except ValueError only for strings.


Is there a way in Python 3.3 to only except ValueError for strings? If I type a string into k, I want "Could not convert string to float" to be printed, rather than "Cannot take the square root of a negative number."

while True:
    try:
        k = float(input("Number? "))

....

    except ValueError:
        print ("Cannot take the square root of a negative number")
        break
    except ValueError:
        print ("Could not convert string to float")
        break

Solution

  • If you want to handle exceptions different depending on their origin, it is best to separate the different code parts that can throw the exceptions. Then you can just put a try/except block around the respective statement that throws the exception, e.g.:

    while True:
        try:
            k = float(input("Number? "))
        except ValueError:
            print ("Could not convert string to float")
            break
        try:
            s = math.sqrt(k)
        except ValueError:
            print ("Cannot take the square root of a negative number")
            break