Basic try-except
Use try to wrap risky code and except to handle errors gracefully. The program won't crash โ it runs the except block instead.
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero!")
Try it Yourself โ
Multiple Except Clauses
You can catch different exception types separately. Each except block handles a specific error, so you can respond appropriately.
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Zero is not allowed.")
except Exception as e:
print(f"Something else: {e}")
Try it Yourself โ
Else and Finally
The else block runs when no exception occurs. The finally block always runs โ perfect for cleanup like closing files.
try:
file = open("test.txt", "r")
except FileNotFoundError:
print("File not found.")
else:
print("File opened successfully.")
file.close()
finally:
print("This always runs.")
Try it Yourself โ