ReviseAlgo Logo

Exception Handling

Custom Exceptions

Creating domain-specific exception classes

Interview: Exception design — tests understanding of exception hierarchy, custom error types, and best practices

Last Updated: June 12, 2026 6 min read

Custom exceptions let you create domain-specific error types that make your code more expressive and easier to debug. They inherit from Exception (or a more specific built-in exception) and can carry custom attributes and messages.

Designing Custom Exceptions

  • Create a base exception class for your module/application
  • Inherit specific exceptions from the base
  • Include useful context in the exception (attributes, messages)
  • Name exceptions with "Error" suffix (e.g., InsufficientFundsError)

Interview Tip

Always create a base exception class for your module. This lets callers catch all your module's errors with a single except clause: except mymodule.MyBaseError.

Use Cases

Domain-specific errors (banking, e-commerce, gaming)

API error hierarchies with HTTP status codes

Library exceptions that users can catch by category

Error reporting with rich context (user ID, resource name, timestamps)

Configuration errors for startup validation

Common Mistakes

Not creating a base exception class for the module

Inheriting from BaseException instead of Exception

Creating too many exception classes (only create when callers need different handling)

Not calling super().__init__(message) — loses the error message

Using exceptions for flow control (exceptions should be exceptional)