DovahKiin DovahKiin - 1 year ago 96
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?

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download