What is the use of raise practically? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the use of raise practically?

15th Jan 2019, 11:39 AM
Aditi Agarwal
Aditi Agarwal - avatar
5 Answers
+ 4
You can use 'raise' to manually raise an exception. Usually, an exception happens 'automatically', for example if you try to divide two numbers and the second one happens to be 0. This will raise a ZeroDivisionException (which can be caught with a try/except statement). To raise an exception by hand, use the 'raise' keyword: if value < 5: raise ValueError('Invalid value') It can be used in a try/except statement too: try: var1/var2 except ZeroDivisionError: print('Tried to divide by 0') # catch exception raise # raise exception that was caught This will first catch the exception, perform some predefined action (here: print a string) and then raise the same exception and terminate the program.
15th Jan 2019, 12:56 PM
Anna
Anna - avatar
+ 1
'raise' can be used to implicitly throw errors, causing the program to fallback into the exception block. This can be used for a matter of scenarios.
15th Jan 2019, 12:18 PM
Dread
Dread - avatar
0
Can you please elaborate on the scenarios?
15th Jan 2019, 12:27 PM
Aditi Agarwal
Aditi Agarwal - avatar
0
What is the purpose of raising an exception manually?
15th Jan 2019, 1:00 PM
Aditi Agarwal
Aditi Agarwal - avatar
0
What is the purpose of raising an exception manually?
15th Jan 2019, 1:00 PM
Aditi Agarwal
Aditi Agarwal - avatar