Chain exceptions with raise from

MediumException Handling Programs · 12 of 20

Write a Python program that converts a low-level error into a clearer one and keeps the cause.

Advertisement
Output
port is missing or not a number | caused by: ValueError

Approach

  1. raise NewError(...) from e stores the original in __cause__.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment