Labs ICT
Pro Login

Custom Exceptions

Creating a Custom Exception

Extend the Exception class to make your own exception types. This is useful when you want to raise domain-specific errors that standard exceptions don't cover.

class NegativeValueError(Exception):
    pass

def sqrt_positive(x):
    if x < 0:
        raise NegativeValueError("Negative input not allowed")
    return x ** 0.5
Try it Yourself →

Custom Exception with a Message

Add an __init__ method to store extra information. The message passed to the constructor can be accessed via str(exception).

class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Need {amount}, have {balance}")

bal = 50
try:
    raise InsufficientFundsError(bal, 200)
except InsufficientFundsError as e:
    print(e)
Try it Yourself →