When should you use custom exceptions in Python?

When should you use custom exceptions in Python?

a) When you need to handle specific error conditions unique to your application
b) When you want to ignore errors and continue execution
c) When you want to raise multiple exceptions at once
d) When you want to automatically fix errors without user intervention

Answer:

a) When you need to handle specific error conditions unique to your application

Explanation:

Custom exceptions should be used in Python when you need to handle specific error conditions that are unique to your application. By defining custom exceptions, you can provide more meaningful error messages and create specialized handlers for these exceptions, making your code more robust and easier to debug.

class InsufficientFundsError(Exception):
    """Exception raised when an account has insufficient funds."""
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        self.message = f"Insufficient funds: tried to withdraw {amount}, but only {balance} available."
        super().__init__(self.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

# Example usage
try:
    account = BankAccount(100)
    account.withdraw(150)
except InsufficientFundsError as e:
    print(e)  # Output: Insufficient funds: tried to withdraw 150, but only 100 available.

In this example, a custom exception InsufficientFundsError is used to handle cases where a withdrawal amount exceeds the available balance. This provides a clear and specific error message that is relevant to the application’s context.

Using custom exceptions enhances the clarity and maintainability of your code, especially in complex applications with unique error handling requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top