Python Built-in Exceptions

Learn the Essentials of Python Exception Handling. Dive into Python's Exception Hierarchy, Syntax, and Best Practices for Error Management in Your Code.
E
Edtoks2:36 min read

Exceptions in Python are events that occur during the execution of a program that disrupts the normal flow of the program. They can be caused by various reasons such as invalid input, file not found, division by zero, etc. Here are some common built-in exceptions in Python:

1. SyntaxError

Raised when there is a syntax error in your code, indicating that the code is not valid in Python.

# SyntaxError example
if x = 5:
    print("x is 5")

2. IndentationError

Raised when there is an issue with the indentation of your code, typically due to incorrect or inconsistent use of spaces or tabs.

# IndentationError example
if x > 10:
print("x is greater than 10")

3. NameError

Raised when a local or global name is not found. This typically occurs when you try to access a variable or function that has not been defined.

# NameError example
print(y)

4. TypeError

Raised when an operation or function is applied to an object of an inappropriate type.

# TypeError example
result = "5" + 3

5. ValueError

Raised when a built-in operation or function receives an argument of the correct type but an inappropriate value.

# ValueError example
int("abc")

6. ZeroDivisionError

Raised when you try to divide a number by zero. 

# ZeroDivisionError example
result = 10 / 0

7. FileNotFoundError

Raised when you try to open or manipulate a file that does not exist.

# FileNotFoundError example
with open("nonexistent.txt", "r") as file:
    content = file.read()

 

8. IndexError

Raised when you try to access an index that is out of range in a sequence (e.g., list, tuple, string).

# IndexError example
my_list = [1, 2, 3]
print(my_list[5])

9. KeyError

Raised when you try to access a dictionary key that does not exist.

# KeyError example
my_dict = {"name": "Alice", "age": 30}
print(my_dict["address"])

10. AttributeError

Raised when you try to access an attribute or method that does not exist for an object.

# AttributeError example
class Person:
    def __init__(self, name):
        self.name = name
person = Person("Alice")

print(person.age)

These are some of the common built-in exceptions in Python. Exception handling allows you to gracefully handle these errors and provide a more user-friendly response or take specific actions when they occur in your program. You can use try, except, else, and finally blocks to manage exceptions in Python code.

Let's keep in touch!

Subscribe to keep up with latest updates. We promise not to spam you.