In Python, it is a good practice to handle errors that may occur during the execution of your code. One common scenario is when a function is called with invalid arguments. Here's an example of how you can handle this scenario:
def divide_numbers(x, y): try: result = x / y except ZeroDivisionError: print("Error: division by zero") else: return result# Call the function with valid argumentsprint(divide_numbers(6, 3)) # Output: 2.0# Call the function with invalid argumentsprint(divide_numbers(6, 0)) # Output: Error: division by zero |
In this example, the divide_numbers function takes two arguments x and y and tries to divide x by y. If y is 0, a ZeroDivisionError will occur. To handle this error, we use a try-except block. If an exception is raised inside the try block, the code inside the corresponding except block will be executed. In this case, we print an error message to the console.
If the try block runs successfully without any exceptions being raised, the code inside the else block will be executed. This block returns the result of the division operation.