DovahKiin DovahKiin - 3 months ago 43
Python Question

What is "Try" and "Except ValueError"?

I've seen "try:" and "except ValueError:" once in a program and I don't know what are they and what are they doing in the code? I would like to understand what it is and its uses in programming to see if I could implement it to some of my own code.

Example I've seen:

a = input()
print("A float")
except ValueError:
print("Not Float")

Why are they being used in this example?


It's because in python sometimes you will have suspcious code that may raise an exception, so you can defend your program by placing the code in a try block. After the try block, including an except statement, followed by a block of code which handles the problem as elegantly as possible (like in the example).