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.
Code
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: NoneHow 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.HTTP Header AnalyzerPaste raw HTTP header lines and get a parsed name-value list with plain-language notes for common headers and security observations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.