except — Easy Examples
Catches and handles exceptions raised in a try block
Catching exceptions
Using except to handle specific errors.
python
# Catch a specific exception try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") # Catch and inspect the exception try: number = int("hello") except ValueError as e: print(f"Error: {e}") # Multiple except blocks try: data = [1, 2, 3] print(data[10]) except IndexError: print("Index out of range") except KeyError: print("Key not found")
Expected Output
Cannot divide by zero! Error: invalid literal for int() with base 10: 'hello' Index out of range
except catches specific exception types. Use 'as e' to access the exception object. Always catch specific exceptions, not bare except.
Want to try these examples interactively?
Open Easy Playground