How to use "raise" keyword in Python
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind
--
Chapters
00:00 How To Use &Quot;Raise&Quot; Keyword In Python
00:19 Accepted Answer Score 408
00:44 Answer 2 Score 61
01:22 Answer 3 Score 51
01:34 Answer 4 Score 24
01:57 Answer 5 Score 18
02:13 Thank you
--
Full question
https://stackoverflow.com/questions/1395...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #keyword #raise
#avk47
ACCEPTED ANSWER
Score 409
It has two purposes.
jackcogdill has given the first one:
It's used for raising your own errors.
if something: raise Exception('My error!')
The second is to reraise the current exception in an exception handler, so that it can be handled further up the call stack.
try:
generate_exception()
except SomeException as e:
if not can_handle(e):
raise
handle_exception(e)
ANSWER 2
Score 61
raise without any arguments is a special use of python syntax. It means get the exception and re-raise it. If this usage it could have been called reraise.
raise
From The Python Language Reference:
If no expressions are present, raise re-raises the last exception that was active in the current scope.
If raise is used alone without any argument is strictly used for reraise-ing. If done in the situation that is not at a reraise of another exception, the following error is shown:
RuntimeError: No active exception to reraise
ANSWER 3
Score 51
ANSWER 4
Score 18
You can use it to raise errors as part of error-checking:
if (a < b):
raise ValueError()
Or handle some errors, and then pass them on as part of error-handling:
try:
f = open('file.txt', 'r')
except IOError:
# do some processing here
# and then pass the error on
raise