Exceptions | Sololearn: Learn to code for FREE!



Can someone explain what the raise command does and why/how someone would use it? I'm just void understanding what the point of raising an error is.

10/20/2016 10:03:56 PM


4 Answers

New Answer


while True: try: user = input("enter a number between 1 and 10, or type done") if user.lower() == 'done': exit() elif user < 1 or user > 10: raise ValueError #or any other name you choose else: print(int(user) **2) break except ValueError: print("Invalid input.") continue #could leave this off if there is no more code within the loop this checks to see if the user input a valid number. if they typed in any letters other than "done" it will raise an error when converting to int, and if they used a number outside the range it will raise an error too. that way we can restart the loop if the input is bad and we only write it out once. this is not the best example, but it shluld help you understand.


Basically, raise tells the computer to CAUSE an error.


It's usable for flow control, if you use some long code: let it be user name database, and some times you get an number but planing to get a name, so you can raise an exception wrong type as function return, and ask user to enter right username.