Python Practice › Exception Handling Programs › Program 12
Chain exceptions with raise from
Write a Python program that converts a low-level error into a clearer one and keeps the cause.
Output
port is missing or not a number | caused by: ValueError
Approach
raise NewError(...) from estores the original in__cause__.
Solution
class ConfigError(Exception): pass def read_port(settings): try: return int(settings["port"]) except (KeyError, ValueError) as e: raise ConfigError("port is missing or not a number") from e try: read_port({"port": "eighty"})except ConfigError as e: print(e, "| caused by:", type(e.__cause__).__name__)Output
port is missing or not a number | caused by: ValueError
Learn the concept
New to this topic? Read the lesson, then come back.