Python Built-in Exceptions
Python provides a wide range of built-in exceptions that are raised when errors occur during execution. These exceptions help you identify what went wrong in your code.
What Are Built-in Exceptions?
Built-in exceptions are predefined error types in Python that are automatically raised for specific types of runtime errors (e.g., ValueError
, TypeError
, ZeroDivisionError
).
Common Built-in Exceptions with Examples
1. ZeroDivisionError
Raised when you divide a number by zero.
x = 10 / 0
Output:
ZeroDivisionError: division by zero
2. ValueError
Raised when a function receives an argument of the correct type but inappropriate value.
x = int("abc")
Output:
ValueError: invalid literal for int() with base 10: 'abc'
3. TypeError
Raised when an operation is applied to an object of an inappropriate type.
x = '5' + 10
Output:
TypeError: can only concatenate str (not "int") to str
4. IndexError
Raised when you try to access an index that is out of range.
lst = [1, 2, 3]
print(lst[5])
Output:
IndexError: list index out of range
5. KeyError
Raised when a dictionary key is not found.
d = {"name": "Alice"}
print(d["age"])
Output:
KeyError: 'age'
6. FileNotFoundError
Raised when trying to open a file that doesn’t exist.
open("nofile.txt")
Output:
FileNotFoundError: [Errno 2] No such file or directory: 'nofile.txt'
7. AttributeError
Raised when an invalid attribute reference is made.
x = 10
x.append(5)
Output:
AttributeError: 'int' object has no attribute 'append'
Full List of Common Built-in Exceptions
Exception | Description |
---|---|
ArithmeticError | Base class for all arithmetic errors |
ZeroDivisionError | Division or modulo by zero |
OverflowError | Result too large to be represented |
TypeError | Invalid type usage |
ValueError | Correct type but inappropriate value |
IndexError | Sequence index out of range |
KeyError | Dict key not found |
NameError | Variable not defined |
FileNotFoundError | File or directory not found |
IOError | Input/output operation failed |
ImportError | Import failed |
ModuleNotFoundError | Specific module not found |
StopIteration | Raised by next() when no items left |
IndentationError | Incorrect indentation |
SyntaxError | Invalid Python syntax |
AttributeError | Object has no such attribute |
MemoryError | Out of memory |
RuntimeError | Errors that don't fall into other categories |