Exceptions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Exceptions

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.

20th Oct 2016, 10:03 PM
hirammvp
hirammvp - avatar
4 Answers
+ 10
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.
20th Oct 2016, 11:25 PM
Luke Armstrong
+ 3
Basically, raise tells the computer to CAUSE an error.
20th Oct 2016, 11:11 PM
1-up Man
1-up Man - avatar
+ 3
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.
21st Oct 2016, 4:49 PM
Dmitrii Sky
Dmitrii Sky - avatar
- 2
Waw
4th Jul 2021, 10:23 AM
Hamza Rahali
Hamza Rahali - avatar