Custom exceptions improve clarity, maintainability, and semantic accuracy by representing domain-specific error conditions.
classInvalidInputError(Exception):pass
Defines a new exception type tailored to your application logic.
2. Basic Custom Exception Example
classNegativeValueError(Exception):passdefprocess_value(value):if value <0:raiseNegativeValueError("Negative values are not allowed")process_value(-10)
Raises a user-defined exception with a meaningful message.
3. Extending Exception with Custom Message
classAgeLimitError(Exception):def__init__(self,age):super().__init__(f"Age {age} is below allowed limit")defvalidate_age(age):if age <18:raiseAgeLimitError(age)validate_age(15)
Adds dynamic context to error messages.
4. Catching Custom Exceptions
Handled like any built-in exception.
5. Creating Hierarchy of Custom Exceptions
Facilitates organized error taxonomy and layered handling.
6. Custom Exception with Additional Attributes
Carries structured metadata for better diagnostics.
7. Using Custom Exceptions in Functions
Enforces logical validation constraints.
8. Custom Exception with Logging
Useful for application-level logging and audit trails.
9. Chaining Custom Exceptions
Preserves original error context using exception chaining.
class FileMissingError(Exception):
pass
def load_config(filename):
if not filename.endswith(".json"):
raise FileMissingError("Only JSON configuration files supported")
load_config("config.txt")
class DataValidationError(Exception):
pass
try:
raise DataValidationError("Invalid CSV column format")
except DataValidationError as e:
print("Validation Error Logged:", e)
class InitialError(Exception):
pass
class DerivedError(Exception):
pass
try:
try:
raise InitialError("Initial failure")
except InitialError as e:
raise DerivedError("Follow-up failure") from e
except DerivedError as final_error:
print(final_error)
class InvalidOrderStateError(Exception):
"""Raised when an order is in an invalid processing state"""
pass
def process_order(status):
if status != "confirmed":
raise InvalidOrderStateError("Order must be confirmed before processing")
process_order("draft")