330

I have read the official definition of "raise", but I still don't quite understand what it does.

In simplest terms, what is "raise"?

Example usage would help.

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Capurnicus
  • 8,171
  • 5
  • 18
  • 11
  • 38
    It's known as `throw` in some other languages. – voithos Dec 19 '12 at 17:29
  • 2
    I guess a relevant addition to this question: does `raise` exits the function automatically or does one need to `return` after `raise`? – alisa May 31 '18 at 18:12

6 Answers6

406

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)
ddejohn
  • 8,775
  • 3
  • 17
  • 30
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 23
    I typed that in and got "global name 'error' is not defined". To others new to Python, you need "raise Exception('My error!')". You replace "error" with your Exception name. A list of standard exceptions you can use is here: http://docs.python.org/2/library/exceptions.html – Curtis Yallop Feb 28 '14 at 16:59
  • 6
    Note that in python 3.x the new syntax is `except SomeException as e:` – P-Gn Nov 10 '16 at 10:18
  • 1
    @user1735003, what does the `as e` do? How is it different from `except SomeException`? – alpha_989 Jan 14 '18 at 02:46
  • 5
    @alpha_989: It lets you get the actual exception instance. – Ignacio Vazquez-Abrams Jan 14 '18 at 02:47
59

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

Sohail Si
  • 2,750
  • 2
  • 22
  • 36
51

It's used for raising errors.

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

Some examples here

Phalgun
  • 1,468
  • 2
  • 15
  • 24
jackcogdill
  • 4,900
  • 3
  • 30
  • 48
24

Besides raise Exception("message") and raise Python 3 introduced a new form, raise Exception("message") from e. It's called exception chaining, it allows you to preserve the original exception (the root cause) with its traceback.

It's very similar to inner exceptions from C#.

More info: https://www.python.org/dev/peps/pep-3134/

Stan Prokop
  • 5,579
  • 3
  • 25
  • 29
  • 2
    When I follow this approach, is it recommended to print the trace on the bottom level where the error occurs, or at the highlest level to that catches the carried error? – alper Apr 28 '20 at 00:12
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
sampson-chen
  • 45,805
  • 12
  • 84
  • 81
13

raise causes an exception to be raised. Some other languages use the verb 'throw' instead.

It's intended to signal an error situation; it flags that the situation is exceptional to the normal flow.

Raised exceptions can be caught again by code 'upstream' (a surrounding block, or a function earlier on the stack) to handle it, using a try, except combination.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • During re-raising and catching the exception to the top level. should I print the `trace` on bottom call where error occurs or the most higher call? or it is recommend to do `raise Exception("message") from e` to carry the error tothe top level? – alper Apr 28 '20 at 00:07
  • 1
    @alper: not sure what you are asking. If you are catching an exception in an `except ...:` handler, the traceback will include the whole stack, from the point where your Python program started up to the place where the exception was raised. So it doesn't matter where in the stack your handler is located, really. If you need to re-raise the exception after handling, use `raise`, *nothing else*. – Martijn Pieters Apr 29 '20 at 11:38
  • 2
    @alper: `raise Exception("message") from e` replaces the `e` exception with a new exception, but just a plain `Exception` instance carries no meaning. If `e` was a `TypeError` or `ValueError` or `LibrarySpecificException` you can't now catch those specific exceptions anymore, because you replaced it with `Exception`. – Martijn Pieters Apr 29 '20 at 11:39