How to use "raise" keyword in Python [duplicate] – Dev

The best answers to the question “How to use "raise" keyword in Python [duplicate]” in the category Dev.

QUESTION:

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.

ANSWER:

It’s used for raising errors.

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

Some examples here

ANSWER:

It has 2 purposes.

yentup 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:

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/

ANSWER:

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