Skip to main content

52. Common Built-in Exceptions

1. Introduction

Python provides many built-in exception types. Knowing the most common ones helps write better error handling.


2. Common Exceptions

  • ValueError → wrong value
int("abc")  # ValueError
  • TypeError → wrong type
"2" + 3  # TypeError
  • IndexError → invalid list index
[1, 2][5]  # IndexError
  • KeyError → missing dictionary key
{"a": 1}["b"]  # KeyError
  • ZeroDivisionError → divide by zero
10 / 0
  • FileNotFoundError → missing file
open("missing.txt")
  • ImportError / ModuleNotFoundError → module not found
import nonexistent
  • AttributeError → attribute doesn’t exist
"hello".not_a_method()

3. Handling Multiple Exceptions

try:
result = 10 / 0
except (ZeroDivisionError, ValueError) as e:
print("Error:", e)

4. Next Steps

✅ You now know common built-in exceptions.
Next: Dates and times in Python.