Stop 06 · Files, Errors & ModulesTopics · 6/9

Raising Custom Exceptions

Part of the Python Roadmap

In short

Catching errors is half the story. Good code also raises clear errors when something is wrong, so problems are caught early and explained in words a teammate understands.

raise stops normal flow and signals an error, and you can define your own exception classes by inheriting from Exception. Custom exceptions make errors clear, such as InsufficientBalanceError in a wallet app.

The jaadu stands behind a bank counter, holding up a red stop paddle as a customer pushes forward an oversized withdrawal slip.

Think of it like this

The bank teller who refuses politely

When you try to withdraw ₹5,000 with ₹3,000 in your account, the teller doesn't just shrug. They stop the transaction and tell you exactly why: insufficient balance. raise is your code stopping the transaction, and a custom exception is the precise reason printed on the slip.

Watch it happen

An error travelling up to someone who can handle it

main()
withdraw()
Exception

withdraw(5000)

1/4main asks the wallet to withdraw ₹5,000.

The big ideas

What you need to know

raise stops the flow

raise ValueError('Age must be positive') ends the current function right there and hands the error to the caller.

Inherit from Exception

class InsufficientBalanceError(Exception): pass is a full custom exception in two lines.

Carry useful data

Give your exception an __init__ that stores details like balance and amount, so handlers can use them.

Chain with from

raise ConfigError('Bad config') from err keeps the original error attached, which makes debugging easier.

See it in code

Walk through the code

python
1class WalletError(Exception):2    """Base class for all wallet problems."""3 4class InsufficientBalanceError(WalletError):5    def __init__(self, balance: float, amount: float):6        self.balance = balance7        self.amount = amount8        super().__init__(f"Need Rs {amount}, have Rs {balance}")9 10def withdraw(balance: float, amount: float) -> float:11    if amount <= 0:12        raise ValueError("Amount must be positive")13    if amount > balance:14        raise InsufficientBalanceError(balance, amount)15    return balance - amount16 17try:18    left = withdraw(3000, 5000)19except InsufficientBalanceError as err:20    print("Declined:", err)21    print("Short by", err.amount - err.balance)22except WalletError:23    print("Some other wallet problem")

1/6A base class groups all your app's errors, so callers can catch them together.

A small family of wallet exceptions with useful details, raised from a function and handled by the caller.

Save yourself the pain

Common mistakes

Oops

Returning -1 or None to signal an error and hoping the caller checks it.

Do this instead

Raise an exception. It can't be silently ignored and it carries a clear message.

Oops

Inheriting custom exceptions from BaseException.

Do this instead

Inherit from Exception. BaseException also covers KeyboardInterrupt and SystemExit, which you shouldn't mix with app errors.

Oops

Writing raise Exception('error') everywhere.

Do this instead

Use a specific built-in (ValueError, TypeError) or your own named class so callers can catch exactly what they expect.

Your mission

Ticket booking errors

~25 min

Quick check

What should a custom exception class usually inherit from?

Go deeper

  1. 1Raise ValueError when a function receives a negative amount.
  2. 2Create an InsufficientBalanceError class and raise it from a withdraw() function.
  3. 3Write clear error messages that say what was wrong and what was expected.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge