Python Built-in Exceptions – Master Error Types & Their Use
Introduction – Why Learn Built-in Exceptions?
When your Python program crashes with messages like IndexError, TypeError, or ZeroDivisionError, it’s not random—it’s Python raising a built-in exception.
Understanding these built-in exceptions helps you:
- Write cleaner, more defensive code
- Debug faster
- Handle errors gracefully with
try...except
In this guide, you’ll learn:
- What built-in exceptions are in Python
- The most common exception types
- Their real-world causes and fixes
- How to use
try...exceptto handle them - Best practices for robust error handling
What Are Built-in Exceptions?
Built-in exceptions are standard error types raised by Python automatically when something goes wrong.
These exceptions are all subclasses of the built-in Exception class.
Most Common Built-in Exceptions
Here’s a quick table of frequently encountered exceptions:
| Exception | Trigger Condition | Example |
|---|---|---|
ZeroDivisionError | Division by zero | 1 / 0 |
ValueError | Invalid value for a function | int("abc") |
TypeError | Wrong data type used | "2" + 2 |
IndexError | List index out of range | mylist[100] |
KeyError | Missing key in dict | mydict["xyz"] |
FileNotFoundError | File doesn’t exist | open("missing.txt") |
AttributeError | Object has no attribute | None.upper() |
ImportError | Module cannot be found | import fake_module |
IndentationError | Improper indentation | wrong tab/space usage |
NameError | Undefined variable used | print(x) (x not defined) |
Example: Handling Built-in Exceptions
ZeroDivisionError
try:
result = 10 / 0
except ZeroDivisionError:
print(" You can't divide by zero.")
ValueError
try:
age = int("twenty")
except ValueError:
print(" Invalid input. Please enter a number.")
FileNotFoundError
try:
with open("data.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print(" The file does not exist.")
Less Common but Important Exceptions
| Exception | When It Happens |
|---|---|
MemoryError | System runs out of memory |
OverflowError | Result too large for data type |
EOFError | Input ends unexpectedly |
RuntimeError | Unspecified internal issue |
StopIteration | Raised by next() in iterators |
AssertionError | assert statement fails |
Special Exceptions (Subclass of BaseException)
| Exception | Description |
|---|---|
SystemExit | Raised when sys.exit() is called |
KeyboardInterrupt | When you press Ctrl+C |
GeneratorExit | Raised when a generator is closed |
These should rarely be caught unless necessary.
Best Practices
| Practice | Why It’s Important |
|---|---|
| Catch specific exceptions | Avoids hiding bugs |
Use finally for cleanup | Ensures resource release |
Avoid catching Exception broadly | Can suppress real problems |
| Always log exception details | Helpful for debugging |
Tip: View All Built-in Exceptions
import builtins
print(dir(builtins))
You’ll see exceptions like ArithmeticError, LookupError, PermissionError, etc.
Summary – Recap & Next Steps
Python has dozens of built-in exceptions to handle invalid inputs, missing files, runtime logic errors, and more.
Key Takeaways:
- Built-in exceptions are raised automatically by Python
- Handle them using
try...exceptfor clean recovery - Know the difference between common ones like
ValueError,TypeError, andKeyError - Avoid overly broad
except:clauses—catch specific errors instead
Real-World Relevance:
Mastering built-in exceptions is essential for stable scripting, debugging, API development, and robust application design.
FAQ – Python Built-in Exceptions
How many built-in exceptions are there?
Python has 60+ built-in exceptions. You can see them via:
help("exceptions")
What is the parent of all exceptions?
All exceptions inherit from the base class Exception, which itself inherits from BaseException.
Can I catch multiple exceptions in one block?
Yes:
except (ValueError, TypeError) as e:
print(e)
Should I catch BaseException?
No. Catch only Exception or its subclasses. Catching BaseException also catches SystemExit and KeyboardInterrupt, which should usually terminate the program.
What’s the difference between IndexError and KeyError?
IndexError: List/tuple index is out of range.KeyError: Dictionary key doesn’t exist.
Share Now :
