What is the correct way to pass an object with a custom exception in Python?

In Python, you can create your own custom exception classes to represent specific types of errors in your program. When you raise these custom exceptions, you can also pass objects (like strings, dictionaries, or custom classes) to provide detailed error information.

Basic Custom Exception with Message

To create a custom exception, inherit from the built-in Exception class and override the __init__() method to accept additional arguments ?

class MyCustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(message)

try:
    raise MyCustomError("Something went wrong!")
except MyCustomError as e:
    print("Caught custom exception:", e.message)
Caught custom exception: Something went wrong!

Passing Dictionary Objects

You can pass structured data like dictionaries to provide detailed error information ?

class DataError(Exception):
    def __init__(self, data):
        self.data = data
        super().__init__(str(data))

try:
    error_info = {"code": 400, "message": "Bad input", "field": "username"}
    raise DataError(error_info)
except DataError as e:
    print("Error code:", e.data["code"])
    print("Error message:", e.data["message"])
    print("Field:", e.data["field"])
Error code: 400
Error message: Bad input
Field: username

Passing Custom Objects

You can pass instances of custom classes to your exceptions for more complex error handling ?

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

class UserError(Exception):
    def __init__(self, user, reason):
        self.user = user
        self.reason = reason
        super().__init__(f"Error with user {user.username}: {reason}")

try:
    user = User("john_doe", "john@example.com")
    raise UserError(user, "Invalid email format")
except UserError as e:
    print(f"User: {e.user.username}")
    print(f"Email: {e.user.email}")
    print(f"Reason: {e.reason}")
User: john_doe
Email: john@example.com
Reason: Invalid email format

Enhanced Custom Exception with Multiple Parameters

You can create more sophisticated exceptions that accept multiple parameters and provide detailed error reporting ?

class ValidationError(Exception):
    def __init__(self, field, value, expected_type):
        self.field = field
        self.value = value
        self.expected_type = expected_type
        super().__init__(f"Invalid {field}: got {type(value).__name__}, expected {expected_type}")
    
    def __str__(self):
        return f"ValidationError: Field '{self.field}' has invalid value '{self.value}' (expected {self.expected_type})"

try:
    raise ValidationError("age", "twenty", "integer")
except ValidationError as e:
    print(e)
    print(f"Field: {e.field}")
    print(f"Invalid value: {e.value}")
    print(f"Expected type: {e.expected_type}")
ValidationError: Field 'age' has invalid value 'twenty' (expected integer)
Field: age
Invalid value: twenty
Expected type: integer

Best Practices

Practice Description
Call super().__init__() Always initialize the base Exception class properly
Use descriptive attribute names Store passed objects with meaningful variable names
Override __str__() Provide clear, human-readable error messages
Include relevant context Pass objects that help with debugging and error handling

Conclusion

Custom exceptions with objects provide powerful error handling capabilities in Python. Always call super().__init__(), use descriptive attributes, and include relevant context to make debugging easier.

Updated on: 2026-03-24T16:20:34+05:30

519 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements