Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you create and raise a custom exception in Python?

SHORT ANSWER

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

python
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: 300

Catching 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 like KeyboardInterrupt and SystemExit.

#python#exceptions#oop

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.