Common Built-in Exceptions
Python provides many built-in exception classes. Knowing the types of errors helps you write appropriate except blocks. In except blocks, always specify a concrete exception class — avoid catching everything with a bare except or except Exception as a general rule.
Common Built-in Exceptions
| Exception Class | When It Occurs |
|---|---|
| ValueError | The type is correct but the value is invalid (e.g., int('abc')). |
| TypeError | An operation is applied to a value of an inappropriate type (e.g., 'text' + 1). |
| KeyError | A dictionary is accessed with a key that does not exist. |
| IndexError | A list is accessed with an index that is out of range. |
| AttributeError | An attribute or method that does not exist on the object is accessed. |
| FileNotFoundError | An attempt is made to open a file that does not exist. |
| ZeroDivisionError | An attempt is made to divide by zero. |
| NameError | An undefined variable is referenced. |
| ImportError | A module import fails. |
| StopIteration | An iterator runs out of items (normally handled automatically). |
| RecursionError | The maximum recursion depth is exceeded. |
| MemoryError | The program runs out of memory. |
| OverflowError | The result of a numeric operation is too large (floats only; ints have arbitrary precision). |
| NotImplementedError | Raised intentionally when a method that a subclass should implement has not been implemented. |
Sample Code
# ValueError: invalid value
try:
n = int('abc')
except ValueError as e:
print(f"ValueError: {e}") # invalid literal for int() with base 10: 'abc'
# TypeError: incorrect type
try:
result = 'Age: ' + 25
except TypeError as e:
print(f"TypeError: {e}") # can only concatenate str (not "int") to str
# KeyError: key not found in dictionary
user = {'name': 'Alice', 'age': 30}
try:
email = user['email']
except KeyError as e:
print(f"KeyError: {e}") # KeyError: 'email'
# IndexError: index out of range
fruits = ['apple', 'banana', 'cherry']
try:
print(fruits[10])
except IndexError as e:
print(f"IndexError: {e}") # list index out of range
# AttributeError: attribute does not exist
try:
'hello'.upper_case() # upper_case() does not exist
except AttributeError as e:
print(f"AttributeError: {e}")
# FileNotFoundError: file does not exist
try:
with open('nonexistent_file.txt') as f:
content = f.read()
except FileNotFoundError as e:
print(f"File not found: {e.filename}")
# ZeroDivisionError: division by zero
try:
result = 100 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Check exception inheritance
print(issubclass(FileNotFoundError, OSError)) # True
print(issubclass(ZeroDivisionError, ArithmeticError)) # True
print(issubclass(ValueError, Exception)) # True
# Inspect the exception object
try:
x = int('abc')
except ValueError as e:
print(type(e).__name__) # ValueError
print(str(e)) # error message
print(e.args) # tuple of error arguments
Overview
Python's exception classes are organized in a hierarchy. At the top is BaseException, with Exception (for regular program errors), KeyboardInterrupt, SystemExit, and others beneath it. In typical error handling, you deal with subclasses of Exception.
Understanding the exception class hierarchy lets you catch errors at the right level of granularity. For example, FileNotFoundError is a subclass of OSError, so you could catch it with except OSError — but specifying FileNotFoundError directly makes your intent clearer.
Silently ignoring an exception with a bare except and pass is an anti-pattern that makes bugs hard to find. At a minimum, add a log statement or print to record that an error occurred.
If you find any errors or copyright issues, please contact us.