How do you create and raise a custom exception in Python?
Subclass Exception (not BaseException), give it a clear name ending in Error, and raise it with raise. Add attributes or a message in __init__ if callers need details. A shared base class lets callers catch a whole family.
Explain it simply
Python's built-in errors are general: ValueError, KeyError. A railway app needs something more specific, like "TicketAlreadyCancelledError". A custom exception names the real problem, so the calling code can catch exactly that and nothing else.
Example
class BankError(Exception):
"""Base class for all bank-related errors."""
class InsufficientFundsError(BankError):
def __init__(self, balance, needed):
super().__init__(f"balance {balance}, needed {needed}")
self.balance = balance
self.needed = needed
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
try:
withdraw(500, 800)
except BankError as e:
print(e) # Output: balance 500, needed 800
print(e.needed - e.balance) # Output: 300Catching BankError also catches InsufficientFundsError, because it is a subclass.
What to say in the interview
"I subclass Exception, name it for the problem, usually with an Error suffix, and keep a project base exception so users can catch all of the library's errors at once. I put useful data in attributes and a readable message through super().__init__()."
Common mistakes
- Inheriting from
BaseException, which is meant for things likeKeyboardInterruptandSystemExit.