Sometimes when working with exceptions we would like to pass custom parameters in an exception. In this blog post, we will show some examples how to do that through creating a custom exception classes using two different methods to pass the exception parameters: Using a dictionary and using instance attributes.

Example

Using a dictionary
class CustomException(Exception):
    def __init__(self, message, **kwargs):
        super().__init__(message)
        self.details = kwargs

try:
    raise CustomException("Something went wrong", 
                         error_code=500, 
                         user_id=123, 
                         timestamp="2025-07-03")
except CustomException as e:
    print(f"Message: {e}")
    print(f"Details: {e.details}")
    print(f"Error code: {e.details['error_code']}")
Using instance attributes
class DatabaseException(Exception):
    def __init__(self, message, **kwargs):
        super().__init__(message)
        for key, value in kwargs.items():
            setattr(self, key, value)

try:
    raise DatabaseException("Connection failed", 
                           host="localhost", 
                           port=5432, 
                           database="mydb")
except DatabaseException as e:
    print(f"Host: {e.host}")
    print(f"Port: {e.port}")
    print(f"Database: {e.database}")