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
# └── ZeroDivisionErrorCreating 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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
