Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

When should you define custom exception classes?

IntermediateConceptExceptions, context managers, files & logging
Answer

When callers need to react differently to different failures. A small hierarchy is enough:

class AuditError(Exception): """Base for this tool."""
class ConfigError(AuditError): ...
class PermissionDenied(AuditError): ...

The CLI entry point catches AuditError and maps subclasses to exit codes and friendly messages, while unexpected exceptions still produce a traceback. Do not create one class per call site; create them per decision a caller makes.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging