How to define custom exception in python? Give me simple and pro examples
- User
How to define custom exception in python? Give me simple and pro examples
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
CustomExceptionthat inherits from theExceptionclass. The constructor takes a message argument and uses thesuper()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
ValidationErrorthat 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
validatefunction. If the validation fails, aValidationErrorexception 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
validatefunction 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, aValidationErrorexception is raised with the errors dictionary as an argument.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.