Reject invalid arguments
Input validation
Python · Const
Python’s raise statement explicitly raises an exception, re-raises the active exception, or chains a new exception to an existing cause.
The raise statement explicitly signals an exception, can re-raise the active exception inside an exception handler, and optionally chains another exception with from. Its operand may be an exception class or instance derived from BaseException.
raise_stmt: "raise" [expression ["from" expression]]| Name | Type | Description |
|---|---|---|
expression | exception class or instance | Exception class or instance to raise; it must be a subclass or instance of BaseException. |
from expression | exception class or instance | Optional exception class or instance used as the explicit cause. |
Does not return normally; it raises an exception or re-raises the active exception.
raise, optionally followed by an exception expression and an optional from expression.from clause records a causal relationship between exceptions.raise is valid only while an exception is actively being handled; otherwise it raises RuntimeError.raise must be an exception class or instance, not an arbitrary value.from becomes the explicit cause when it is an instance.def parse_port(value):
try:
port = int(value)
except ValueError as exc:
raise ValueError("port must be an integer") from exc
if not 1 <= port <= 65535:
raise ValueError("port out of range")
return port
try:
parse_port("http")
except ValueError as exc:
print(exc)The function validates a port, raises a clearer exception, and preserves the original conversion error through chaining.
Input validation
Error translation
Exception handling
Traceback control
raise take?raise SomeError raises an exception class, which Python instantiates without arguments when needed. raise SomeError("detail") raises an already-created exception instance; both must derive from BaseException.
Follow-up: What does bare raise do? Inside an exception handler it re-raises the active exception; outside one, it produces RuntimeError.
raise mean?Bare raise re-raises the exception currently being handled, preserving the active exception. It is commonly used in an except block after logging or cleanup.
Follow-up: How can a handler add context while retaining the original failure? Use raise NewError(...) from original, which establishes explicit exception chaining.
raise ... from ...?The optional from expression enables exception chaining. The second expression must be an exception class or instance, and an instance is recorded as the raised exception’s __cause__.
Follow-up: How can an exception be given a particular traceback? Call with_traceback() on the exception and raise the returned same instance.
tryexceptBaseExceptionExceptionwith_traceback()__cause____traceback__