Using try, except inside a function in the following code producing a correct result.
def try_function():
try:
hrs = float(raw_input("Enter Hours: "))
rate = float(raw_input("Enter Rate: "))
return hrs * rate
except:
print "Values are non numeric"
quit()
pay = try_function()
print pay
I got the following result:
Enter Hours: 20
Enter Rate: 10
200.0
While if i change the code to the following i get not result:
def try_function():
try:
hrs = float(raw_input("Enter Hours: "))
rate = float(raw_input("Enter Rate: "))
except:
print "Values are non numeric"
quit()
return hrs * rate
pay = try_function()
print pay
Here what i get :
Enter Hours: 20
Enter Rate: 10
I don't know why i am not getting the value 200, and which way is better the first or the second?
Thank you.
except:is usually a very bad idea, as it will also catch special exceptions likeKeyboardInterruptandStopIteration. you almost always wantexcept Exception:, or in this case, a more specific type likeexcept ValueError:.