Skip to content
Python Programming

Exception Handling in Python

Beginner Lesson 9 of 10

Learn to handle errors and exceptions gracefully in your Python programs.

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Error: {e}")
else:
print("Success!")
finally:
print("This always runs")
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
# Custom exceptions
class InvalidEmailError(Exception):
pass
  • ValueError - Invalid value
  • TypeError - Wrong type
  • KeyError - Dict key not found
  • IndexError - Index out of range
  • FileNotFoundError - File doesn’t exist
  • ZeroDivisionError - Division by zero

Continue to Advanced Python →