raise from Chains The Original Exception

raise ... from keeps the caught exception as __cause__ so tracebacks and log aggregators show the root failure next to the rewritten error.

PythonResilience

Code

pythonsnippet
27 lines
def parse_port(raw: str) -> int:
    try:
        return int(raw)
    except ValueError as exc:
        # from 保留原始异常作为 __cause__,而不是覆盖它
        raise ValueError(f"invalid port: {raw!r}") from exc


def parse_port_quiet(raw: str) -> int:
    try:
        return int(raw)
    except ValueError:
        # from None 隐藏上下文:用户只看到干净的消息
        raise ValueError(f"invalid port: {raw!r}") from None


try:
    parse_port("8080a")
except ValueError as err:
    print("message :", err)
    print("cause   :", type(err.__cause__).__name__)
    print("original:", err.__cause__)

try:
    parse_port_quiet("x")
except ValueError as err:
    print("quiet   :", err, "| cause:", err.__cause__)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

message : invalid port: '8080a'
cause   : ValueError
original: invalid literal for int() with base 10: '8080a'
quiet   : invalid port: 'x' | cause: None

How it works

The working surface is the functions parse_port and parse_port_quiet — everything else is wiring.

ValueError appears at a raise inside an except handler — it fires only while that failure type is already being handled.

Using it

The primary signature is def parse_port(raw: str) -> int

Output lines are prefixed (message :, original:), making each step’s effect easy to spot.

The surface worth importing is parse_port; the helpers around it are private to the snippet.

Key statements

def parse_port_quiet(raw: str) -> int:
    try:
        return int(raw)
    except ValueError:
        # from None 隐藏上下文:用户只看到干净的消息
        raise ValueError(f"invalid port: {raw!r}") from None
def parse_port(raw: str) -> int:
    try:
        return int(raw)
    except ValueError as exc:
        # from 保留原始异常作为 __cause__,而不是覆盖它
        raise ValueError(f"invalid port: {raw!r}") from exc
except ValueError as err:
    print("message :", err)
    print("cause   :", type(err.__cause__).__name__)
    print("original:", err.__cause__)

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `ValueError` fires only while that failure type is already being handled, not on its own trigger.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `parse_port`, `parse_port_quiet` at load time.