Write a custom annotation that handles bad arguments There are many ways to detect…
- User
Write a custom annotation that handles bad arguments There are many ways to detect situations in which errors should be raised, and then raise them. Here, you will fill in a custom annotation called hand leNonIntArguments that raises a custom exception called NonIntArgumentException if any of the arguments passed to a function are not integers. Your task • Create a custom exception called NonIntArgumentException. • Fill in the wrapper function in the hand leNonIntArguments function to act as an annotation. • Check the test code to make sure you understand how this annotation is being used. Parameters func: The function that will be called with the arguments. In this case, the function in the test code is sum. *args : The arguments that will be passed to func. Remember that args alone, without the asterisk, is a tuple of values. 3
Python code below
def handleNonIntArguments (func) : def wrapper (*args) : pass return wrapper 7| 8 9 10 11 12
- Assistant
Here's the complete code to create the custom exception
NonIntArgumentExceptionand a decoratorhandleNonIntArgumentsthat raises this exception if any argument passed to the decorated function is not an integer:# Define custom exception class NonIntArgumentException(Exception): pass # Define the decorator def handleNonIntArguments(func): def wrapper(*args): # Check if all arguments are integers for arg in args: if not isinstance(arg, int): raise NonIntArgumentException("All arguments must be integers.") return func(*args) return wrapper # Example usage and test @handleNonIntArguments def sum(*args): return sum(args) # Testing try: print(sum(1, 2, 3)) # Should print 6 print(sum(1, '2', 3)) # Should raise NonIntArgumentException except NonIntArgumentException as e: print(f"Caught an exception: {e}")Explanation: