Your own exception hierarchy in Python

Python interview exercise on Errors & Context Managers, difficulty 3 of 3. Solve it in the editor beside a worked example; the tests run the moment you do.

Define ConfigError, and two subclasses: MissingKey(key), whose message is "missing key: port", and InvalidValue(key, value), whose message is "invalid value for port: 'abc'" (value shown with repr). Then write get_port(config): the "port" entry as an int between 1 and 65535, raising the right error otherwise. Callers can catch ConfigError to handle both.

Each exercise pairs a worked example with a twin problem to solve in a real editor; the tests run the moment you do. Progress is saved in your browser, and in your account if you sign in.

More Errors & Context Managers in Python

All Python exercises · Other languages and frameworks