Handle errors gracefully instead of crashing.
try:
number = int(input("Enter a number: "))
print(f"You entered: {number}")
except:
print("That's not a valid number!")
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid value!")
Always runs, whether there's an error or not:
try:
file = open("data.txt")
# Do something
except FileNotFoundError:
print("File not found!")
finally:
print("Cleanup complete")
Runs if NO exception occurred:
try:
number = int("42")
except ValueError:
print("Error!")
else:
print(f"Success! Number is {number}")
Interactive Visualization