class CustomError(Exception): pass # Raising the custom exception def example_function(x): if x < 0: raise CustomError("CustomError: Negative value not allowed") try: example_function(-5) except CustomError as e: print(e)
CustomError: Negative value not allowed
class ValueTooSmallError(Exception): def __init__(self, message, value): super().__init__(message) self.value = value def example_function(x): if x < 0: raise ValueTooSmallError(f"ValueTooSmallError: {x} is less than 0", x) try: example_function(-5) except ValueTooSmallError as e: print(f"{e}: The value is {e.value}")
ValueTooSmallError: -5 is less than 0: The value is -5
class MyBaseError(Exception): """Base class for exceptions in this module.""" pass class NetworkError(MyBaseError): """Exception raised for network-related errors.""" def __init__(self, message="Network error occurred"): self.message = message super().__init__(self.message) class DatabaseError(MyBaseError): """Exception raised for database-related errors.""" def __init__(self, message="Database error occurred"): self.message = message super().__init__(self.message) # Raising different custom exceptions def network_operation(): raise NetworkError() def database_operation(): raise DatabaseError() try: network_operation() except NetworkError as e: print(e) except DatabaseError as e: print(e)
Network error occurred
class InsufficientFundsError(Exception): def __init__(self, balance, amount): super().__init__(f"Insufficient funds: Cannot withdraw {amount}, balance is {balance}") self.balance = balance self.amount = amount 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 # Testing the custom exception in a banking scenario account = BankAccount(100) try: account.withdraw(150) except InsufficientFundsError as e: print(e)
Insufficient funds: Cannot withdraw 150, balance is 100