Python / Core Python Fundamentals Interview Questions
What is the Python exception class hierarchy and how do you create custom exceptions?
Python exceptions form a class hierarchy rooted at BaseException. Most exceptions you deal with inherit from Exception, which itself inherits from BaseException. The hierarchy determines which except clauses match a raised exception — a handler for a parent class catches instances of all child classes.
# BaseException # âââ SystemExit # sys.exit() # âââ KeyboardInterrupt # Ctrl-C # âââ GeneratorExit # generator.close() # âââ Exception # all regular exceptions # âââ ValueError # âââ TypeError # âââ AttributeError # âââ KeyError # âââ IndexError # âââ RuntimeError # â âââ RecursionError # âââ OSError # â âââ FileNotFoundError # â âââ PermissionError # âââ ArithmeticError # âââ ZeroDivisionError
Creating custom exceptions is simple — subclass Exception (or a more specific built-in) and optionally add an __init__ for structured error data:
class InsufficientFundsError(ValueError): def __init__(self, balance, amount): self.balance = balance self.amount = amount super().__init__( f'Cannot withdraw {amount}; balance is only {balance}') def withdraw(account, amount): if amount > account.balance: raise InsufficientFundsError(account.balance, amount) account.balance -= amount try: withdraw(acc, 9999) except InsufficientFundsError as e: print(e) # Cannot withdraw 9999; balance is only 1500 print(e.amount) # 9999 â structured access
More Related questions...