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

ExceptionDescription
ArithmeticErrorBase class for all arithmetic errors
ZeroDivisionErrorDivision or modulo by zero
OverflowErrorResult too large to be represented
TypeErrorInvalid type usage
ValueErrorCorrect type but inappropriate value
IndexErrorSequence index out of range
KeyErrorDict key not found
NameErrorVariable not defined
FileNotFoundErrorFile or directory not found
IOErrorInput/output operation failed
ImportErrorImport failed
ModuleNotFoundErrorSpecific module not found
StopIterationRaised by next() when no items left
IndentationErrorIncorrect indentation
SyntaxErrorInvalid Python syntax
AttributeErrorObject has no such attribute
MemoryErrorOut of memory
RuntimeErrorErrors that don't fall into other categories