When passing invalid arguments to a function, Python may raise different types of exceptions depending on the nature of the error. Here's an example of how you can handle invalid argument errors:
def calculate_area(width, height): try: area = width * height except TypeError as error: print(f"Error: {error}") else: return area# Call the function with valid argumentsprint(calculate_area(5, 6)) # Output: 30# Call the function with invalid argumentsprint(calculate_area('5', 6)) # Output: Error: can't multiply sequence by non-int of type 'int' |
In this example, the calculate_area function takes two arguments width and height and tries to calculate the area of a rectangle. If any of the arguments are not of the expected type, a TypeError will occur. To handle this error, we use a try-except block. The except block catches the exception and prints an error message that includes the exception's message.
It's worth noting that not all exceptions have messages like TypeError. Some exceptions may only have a name, such as ValueError or NameError. To handle these types of exceptions, you can simply use the exception's name in the except block:
def get_first_item(items): try: return items[0] except IndexError: print("Error: the list is empty") |
In this example, the get_first_item function takes a list of items and tries to return the first item in the list. If the list is empty, an IndexError will occur. We catch this exception in the except block and print an error message to the console.