Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 3 of 10 · Exception Handling & Debugging
Interview question

How do you create and raise custom exceptions in Python? Python में custom exceptions कैसे बनाएं और raise करें?

Answer

Custom exceptions are created by subclassing Exception (or a more specific built-in exception), allowing you to represent domain-specific error conditions clearly.

class InsufficientFundsError(Exception):
    """Raised when a withdrawal exceeds the account balance."""
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        message = f'Cannot withdraw {amount}, balance is only {balance}'
        super().__init__(message)

class BankAccount:
    def __init__(self, balance):
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(self.balance, amount)
        self.balance -= amount
        return self.balance

account = BankAccount(100)
try:
    account.withdraw(150)
except InsufficientFundsError as e:
    print(e)  # Cannot withdraw 150, balance is only 100
    print(e.balance, e.amount)  # access custom attributes

# Building an exception hierarchy for a project
class AppError(Exception):
    """Base exception for the application."""
    pass

class ValidationError(AppError):
    pass

class NotFoundError(AppError):
    pass

# Callers can catch the base class to handle ANY app-specific error
try:
    raise ValidationError('Invalid email format')
except AppError as e:
    print(f'App error: {e}')

Custom exceptions Exception (या किसी specific built-in exception) को subclass करके बनाई जाती हैं, domain-specific error conditions को clearly represent करने के लिए।

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

class BankAccount:
    def __init__(self, balance):
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(self.balance, amount)
        self.balance -= amount
        return self.balance

account = BankAccount(100)
try:
    account.withdraw(150)
except InsufficientFundsError as e:
    print(e)
    print(e.balance, e.amount)

# Exception hierarchy बनाना
class AppError(Exception):
    pass

class ValidationError(AppError):
    pass

try:
    raise ValidationError('Invalid email format')
except AppError as e:
    print(f'App error: {e}')

Was this answer clear?