Python Exceptions: The Ultimate Beginners Guide (With Examples)

In Python, Exceptions are parts of your programming journey. Whether you are a beginner or an experienced Python programmer, understanding exceptions is essential for writing dependable and error-free code.

So, in the first part of the Python Exception Handling series, we will primarily discuss Python exceptions. Moreover, we will also discuss the most common exceptions, how they occur, and how to handle them effectively.

What are Exceptions in Python

Python Exceptions are referred to as the events that occur during the program execution. These types of events disrupt the normal code flow. Moreover, they are raised when unexpected conditions or errors are encountered.

Exceptions assist in handling and recovering from errors and also prevent the programs from crashing abruptly.

What are built-in exceptions in Python

Here, we have listed the most common built-in exceptions in Python:

Exception Description
ZeroDivisionError Occurs when an attempt is made to divide by zero.
ValueError Arises when a function accepts an unsuitable value.
TypeError Arises when an operation is incompatible with the defined data type.
IndexError Arises when a sequence index becomes out of range.
KeyError Occurs when a dictionary key is not found.
FileNotFoundError Arises when you attempt to access a non-existent file.
NameError Arises when a local or global name is not recognized.
AttributeError Arises when an attribute assignment or reference fails.
ImportError Occurs when an import statement fails.
ModuleNotFoundError Arises when a module cannot be located.
IndentationError Occurs when incorrect indentation is detected.
SyntaxError Arises when a syntax mistake has been identified.
RuntimeError Arises when a generic runtime error takes place.
AssertionError Arises when an assert statement fails.
NotImplementedError Arises when an abstract method lacks an implementation.
OverflowError Arises when an arithmetic operation yields a large result.
FloatingPointError Arises when a floating-point operation fails.
IOError Arises when an input/output operation fails.
OSError Arises when an operating system-related error takes place.
MemoryError Arises when an operation exhausts memory resources.
RecursionError Arises when the maximum recursion depth is exceeded.
KeyboardInterrupt Occurs when the user interrupts program execution.
SystemError Arises when an internal error is detected by the interpreter.
SystemExit Occurs when a program exit is requested using “sys.exit()”.
UnboundLocalError Arises when a local variable is referenced before the assignment.
UnicodeError Arises when Unicode-related issues are encountered.

Now, let’s check some code examples for the most common exceptions.

1. “NameError” Exception

The given codes try to print an undefined variable and then handle the “NameError” by displaying the given error message.

try:
    print(variable)
except NameError:
    print("Error: Variable not defined")

2. “TypeError” Exception

Here, we attempted to add a string and an integer that triggers the “TypeError” exception. This exception will be handled by the “except” block.

try:
    result = "5" + 3
except TypeError:
    print("Error: Unsupported operand types")

3. “ValueError” Exception

This code tries to convert a string to an integer but will encounter characters that can not be converted. Resultantly, it will lead to a “ValueError” exception.

try:
    number = int("abc")
except ValueError:
    print("Error: Invalid conversion to int")

4. “ZeroDivisionError” Exception

In the following program, the division by zero operation will throw the “ZeroDivisionError” handled by the try-except blocks.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero")

5. “FileNotFoundError” Exception

Calling the non-existent file will cause the “FileNotFound” error.

try:
    with open("xyz.txt") as file:
        content = file.read()
except FileNotFoundError:
    print("Error: File not found")

6. “IndexError” Exception

Accessing an index that is beyond the range of the specified list will generate the “IndexError” error.

my_list = [1, 2, 3]
try:
    value = my_list[5]
except IndexError:
    print("Error: Index out of range")

7. “KeyError” Exception

Accessing a non-existent dictionary key will throw the “KeyError” exception.

my_dict = {"name": "Sharqa", "age": 25}
try:
    value = my_dict["location"]
except KeyError:
    print("Error: Key not found in dictionary")

8. “AttributeError” Exception

Here, the “AttributeError” exception will be thrown when the non-existent method will be invoked on a string.

try:
    result = "Hello".length()
except AttributeError:
    print("Error: Object has no attribute")

9. “ImportError” Exception

The “ImportError” exception will be triggered here when the code tries to import any non-existent module.

try:
    import non_existent_module
except ImportError:
    print("Error: Module not found")

10. “IndentationError” Exception

Due to incorrect code structure, the “IndentationError” exception will be thrown.

def my_function():
print("Hello")

In this case, we have defined a function without proper indentation.

11. “LookupError” Exception

In case accessing an index that is beyond the range of a list will cause the “LookupError“.

my_list = [1, 2, 3]
try:
    value = my_list[5]
except LookupError:
    print("Error: Lookup failed")

12. “FileExistsError” Exception

Here, the given program tries to create a new file with the “x” mode or the exclusive file. This led to the “FileExistsError” exception.

try:
    with open("existing_file.txt", "x") as file:
        file.write("Hello")
except FileExistsError:
    print("Error: File already exists")

13. “PermissionError” Exception

If you try to open and write to a file in a directory where you have the relevant permissions, then the “PermissionError” exception will be thrown.

try:
    with open("/etc/somefile.txt", "w") as file:
        file.write("Hello")
except PermissionError:
    print("Error: Permission denied")

14. “EnvironmentError” Exception

Opening a non-existent file will also result in an “EnvironmentError” exception if it is due to an environment-related issue.

try:
    with open("non_existent_file.txt") as file:
        content = file.read()
except EnvironmentError:
    print("Error: Environment-related error")

15. “EOFError” Exception

The given program prompts the user for input and captures the “EOFError“. This happens when the end of the input streams has been reached unexpectedly.

try:
    data = input("Enter data: ")
except EOFError:
    print("Error: End of file reached")

16. “RuntimeError” Exception

Here, we will define a function that will raise the “RuntimeError” exception with a customized message.

def raise_runtime_error():
    raise RuntimeError("Custom runtime error")
try:
    raise_runtime_error()
except RuntimeError as e:
    print("Error:", e)

17. “NotImplementedError” Exception

In the given code, a class has been defined as having an unimplemented method that will trigger the “NotImplementedError” exception.

class MySubclass:
    def my_method(self):
        raise NotImplementedError("Method not implemented")
obj = MySubclass()
try:
    obj.my_method()
except NotImplementedError as e:
    print("Error:", e)

18. “RecursionError” Exception

Here, the recursive function has been defined without the base case, which will ultimately throw the “RecursionError” exception.

def recursive_function(n):
    return recursive_function(n - 1)
try:
    recursive_function(10)
except RecursionError:
    print("Error: Maximum recursion depth exceeded")

19. “StopIteration” Exception

According to this program, first, an iterator has been created and a while loop is used for iterating through it until it raises the “StopIteration” exception. This signifies the end of iteration and displays the error message.

my_iter = iter([1, 2, 3])
try:
    while True:
        print(next(my_iter))
except StopIteration:
    print("Error: Iteration stopped")

20. “SystemExit” Exception

The given code attempts to exit with the “sys.exit()“, throwing the “SystemExit” exception, which is caught using the except block.

try:
    sys.exit("Exiting the program")
except SystemExit as e:
    print("Error:", e)

21. “KeyBoardInterrupt” Exception

This program enters an infinite loop and waits for the keyboard (CTRL+C), which captures the”“KeyBoardInterrupt” error.

try:
    while True:
        pass
except KeyboardInterrupt:
    print("Error: Keyboard interrupt detected")

22. “GeneratorExit” Exception

Here, the given generator function yields a value and tries to close it explicitly. This condition leads to the “GeneratorExit” exception.

def my_generator():
    try:
        yield 1
    finally:
        print("Generator closing")
gen = my_generator()
next(gen)
try:
    gen.close()
except GeneratorExit:
    print("Error: Generator closing")

23. Generic “Exception”

Dividing by zero operation will throw the generic “Exception” being caught by the except block.

try:
    result = 10 / 0
except Exception as e:
    print("Error:", e)

24. “FloatingPointsError” Exception

Here, dividing a floating point value with zero triggers the “FloatingPointError” exception.

try:
    result = 1.0 / 0.0
except FloatingPointError:
    print("Error: Floating point error")

25. “OSError” Exception

Opening a non-existent file also throws the “OSError” exception, specifically if it is an operating system-related issue.

try:
    with open("non_existent_file.txt") as file:
        content = file.read()
except OSError:
    print("Error: Operating system error")

26. “OverflowError” Exception

Creating a large number will cause an “OverflowError” exception. This also signifies that the numeric representation limit has been exceeded.

try:
    large_number = 10 ** 10000
except OverflowError:
    print("Error: Overflow error")

27. “MemoryError” Exception

In the given code, we have defined a function that created an excessively large list. This led to “MemoryError“.

def create_large_list():
    my_list = [0] * (10 ** 8)
try:
    create_large_list()
except MemoryError:
    print("Error: Insufficient memory")

Handle Exceptions Using try-except in Python

The “try” and “except” blocks can be utilized for catching and handling the exceptions gracefully. These blocks also prevent your program from crashing.

Here, in the given example, the “divide()” function is defined that accepts two numbers “num1” and “num2” as its arguments. If a “ZeroDivisionError” occurs, the “except” block will catch the exception and the added message will be displayed with the print() function.

def divide(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        return "Cannot divide by zero"

num1 = 10
num2 = 0
result = divide(num1, num2)
print(result)
Handle an Exceptions Using try-except in Python
Handle Exceptions Using try-except in Python

Handle Multiple Exceptions in Python

Multiple exceptions can be added for handling different exceptions separately. This enables you to provide particular error handling based on the type of exception.

According to the given program, the “calculate_value()” function tries to convert the input to an integer and perform a division. This function handles two different exceptions:

    • ValueError” if the input is not a valid number.

li>”ZeroDivisionError” if the division by zero is attempted.

Based on the particular exceptions, the added messages will be shown on the console.

def calculate_value(data):
    try:
        value = int(data)
        result = 10 / value
        return result
    except ValueError:
        return "Invalid input: Not a number"
    except ZeroDivisionError:
        return "Cannot divide by zero"

data1 = "5"
data2 = "0"
print(calculate_value(data1))
print(calculate_value(data2))
Handle Multiple Exceptions in Python
Handle Multiple Exceptions in Python

In the next part of this series, we will discuss Python Exception Handling in detail.

Conclusion

Understanding Python exceptions is essential for writing reliable and robust code. By handling potential errors, you can avoid unexpected crashes and improve the user experience.

More specifically, you can utilize the “try” and “except” that offers an organized way for managing exceptions. They also permit the program to recover from the encountered error.

Want to explore and learn more related to Python, do check out our dedicated Python Tutorial Series!

If you read this far, tweet to the author to show them you care. Tweet a thanks
As a professional content writer with 3 years of experience, I specialize in creating high-quality, SEO-optimized content that engages, attracts, and retains the audience.

Each tutorial at GeeksVeda is created by a team of experienced writers so that it meets our high-quality standards.

Join the GeeksVeda Weekly Newsletter (More Than 5,467 Programmers Have Subscribed)
Was this article helpful? Please add a comment to show your appreciation and support.

Got Something to Say? Join the Discussion...