QA
Beginner LevelPython

How do you create custom Exception classes in Python?

❓ Interview Prompt: Explain inheriting from `Exception` base class, custom error attributes, custom error messages, and exception hierarchies.

To create custom exceptions, define a new class that inherits from Python's built-in 'Exception' base class (or a specific subclass like 'ValueError'):

Best Practice:

•
Inherit from 'Exception' (NOT 'BaseException', which catches 'KeyboardInterrupt' and 'SystemExit'!).
•
Define custom domain exception hierarchies for clean error handling in SDKs and APIs.

Code Implementation Example

python
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f'Cannot withdraw ${amount}. Current balance is ${balance}.')

# Usage:
def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount
💡Defining and raising custom domain exception classes.
🎯 Interview Key Takeaway

Inherit custom exceptions from Exception and attach domain metadata attributes to simplify error handling.

#Exceptions#Custom Exceptions#OOP#Beginner
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?