The Python Oracle

How to use "raise" keyword in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Question
00:25 Accepted answer (Score 403)
00:58 Answer 2 (Score 55)
01:46 Answer 3 (Score 51)
02:03 Answer 4 (Score 23)
02:34 Thank you

--

Full question
https://stackoverflow.com/questions/1395...

Accepted answer links:
[jackcogdill has given the first one:]: https://stackoverflow.com/a/13957849/208...

Answer 2 links:
[The Python Language Reference]: https://docs.python.org/2/reference/simp...

Answer 3 links:
[here]: http://infohost.nmt.edu/tcc/help/pubs/py...

Answer 4 links:
https://www.python.org/dev/peps/pep-3134/

--

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


It's used for raising errors.

if something:
    raise Exception('My error!')

Some examples here




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