0
What is the use of raise practically?
5 Respostas
+ 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.
+ 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.
0
Can you please elaborate on the scenarios?
0
What is the purpose of raising an exception manually?
0
What is the purpose of raising an exception manually?