How do you handle exceptions in Python? Can you provide an example of how you catch and handle different types of exceptions?
In Python, exceptions are handled using try
, except
, and optionally finally
blocks. Here's an example of catching and handling different types of exceptions:
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Invalid value!") except Exception as e: print("An error occurred:", e) finally: print("Cleanup code here...")
In this example, if a ZeroDivisionError
occurs, it prints a message, and if a ValueError
occurs, it prints a different message. If any other exception occurs, it prints the error message. The finally
block is used for cleanup code that needs to be executed whether an exception occurs or not.