This question already has an answer here:
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.
This question already has an answer here:
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.
You can use it to raise errors as part of error-checking:
Or handle some errors, and then pass them on as part of error-handling:
Besides
raise Exception("message")
andraise
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/
It's used for raising errors.
Some examples here
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 calledreraise
.From The Python Language Reference:
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
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.It has 2 purposes.
yentup has given the first one.
The second is to reraise the current exception in an exception handler, so that it can be handled further up the call stack.