Python Reference ยท Statements and Keywords
The raise statement
Reference for the Python raise statement: raise an exception class or instance, re-raise with a bare raise, chain with from, and avoid common mistakes.
The raise statement signals an error by starting exception handling. Execution stops at the raise, the interpreter unwinds the call stack, and the exception propagates until an except clause handles it or the program ends with a traceback.
Raise exceptions when a function cannot do what it promises: invalid argument, missing resource, broken invariant. Callers can then decide what to do, instead of receiving a quietly wrong result.
if age < 0: raise ValueError("age cannot be negative")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
raise raise ExceptionClass raise ExceptionClass(args) raise exception_instance from other_exception raise exception_instance from None
| Form | Description |
|---|---|
raise |
Re-raises the exception currently being handled. Outside an except block it raises RuntimeError: No active exception to reraise. |
raise Cls |
Instantiates Cls() with no arguments and raises it. |
raise obj |
Raises an existing exception instance. It must derive from BaseException. |
from cause |
Sets __cause__ to cause, shown in the traceback as the direct reason. |
from None |
Suppresses the automatic context so the traceback shows only the new error. |
Raises: TypeError if the object is not an exception class or instance.
Usage notes
- Pick the most specific built-in (
ValueError,TypeError,KeyError,FileNotFoundError) before inventing a class. Define a custom exception when callers should be able to catch your errors specifically. - Write useful messages. Include the offending value, using
!rfor strings, and say what was expected. - Implicit context. Raising inside an
exceptblock automatically stores the old exception in__context__and the traceback prints "During handling of the above exception, another exception occurred". - Use
raisenotraise errto re-raise: the bare form keeps the original traceback intact and is clearer. NotImplementedErrormarks abstract methods;NotImplemented(the constant) is a different thing used by binary operator methods.- Do not raise strings or other objects. That has not been possible since Python 3.
StopIterationinside a generator is converted toRuntimeError(PEP 479); usereturnto end a generator.- Validate at boundaries. Raising is for exceptional situations; for expected outcomes, returning
Noneor a result object can be better.