Skip to content
TheChatArchiveThe Chat Archive
Ai2tulu-2-dpo-70b· Ai2Hugging Face Arena Human Preference 55K

How to define custom exception in python? Give me simple and pro examples

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-3.5-turbo-0125’s answer.
  1. User

    How to define custom exception in python? Give me simple and pro examples

  2. Ai2 Assistant

    To define a custom exception in Python, you can create a new class that inherits from the built-in Exception class or one of its subclasses. Here's a simple example:

    class CustomException(Exception):
        def __init__(self, message):
            super().__init__(message)
            self.message = message
    
    # Example usage
    try:
        raise CustomException("Something went wrong")
    except CustomException as e:
        print(e.message)
    

    In this example, we define a new exception class called CustomException that inherits from the Exception class. The constructor takes a message argument and uses the super() function to call the parent class's constructor, passing the message to it.

    To use the custom exception, we raise an instance of it and catch it in a try-except block. In the except block, we print the message associated with the exception.

    Here's a more advanced example that demonstrates how to define a custom exception with additional functionality:

    class ValidationError(Exception):
        def __init__(self, message, errors):
            super().__init__(message)
            self.message = message
            self.errors = errors
    
        def __str__(self):
            return f"{self.message}\nErrors: {self.errors}"
    
    # Example usage
    data = {'name': 123, 'email': 'example.com'}
    errors = {}
    
    try:
        validate(data)
    except ValidationError as e:
        print(e)
    
    def validate(data):
        errors = {}
        if not isinstance(data.get('name'), str):
            errors['name'] = "must be a string"
        if not isinstance(data.get('email'), str):
            errors['email'] = "must be a string"
        if '@' not in data.get('email'):
            errors['email'] += " must be a valid email address"
        if errors:
            raise ValidationError("Validation failed", errors)
    

    In this example, we define a new exception class called ValidationError that also takes a dictionary of errors as its argument. The __str__ method is overridden to provide a more informative string representation of the exception object.

    In the example usage, we define a dictionary of data and an empty dictionary of errors. We then try to validate the data using the validate function. If the validation fails, a ValidationError exception is raised with a message and the errors dictionary as arguments.

    In the except block, we print the exception object, which will include the custom message and errors dictionary.

    The validate function demonstrates how to use the custom exception. It iterates over the data dictionary and checks if each value is of the expected type. If not, it adds a message to the errors dictionary for that key. If there are any errors, a ValidationError exception is raised with the errors dictionary as an argument.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.