Examples of Python Exceptions

Comprehensive Examples of Python Exceptions

Here are examples of common Python exceptions with simple programs:

1. SyntaxError

# Missing colon
if True
    print("Hello")

# Missing parenthesis
print("Hello"

2. IndentationError

def my_function():
print("Indented wrong")  # Missing indentation

if True:
    print("Proper")
     print("Wrong indentation")  # Inconsistent indentation

3. NameError

print(undefined_variable)  # Variable not defined

def my_func():
    print(non_existent)

my_func()

4. TypeError

# Adding incompatible types
result = "5" + 3

# Wrong number of arguments
def greet(name):
    return f"Hello {name}"

greet()  # Missing argument

# Invalid operation on type
len(42)  # Integer has no length

5. ValueError

# Invalid conversion
number = int("abc")

# Invalid value for function
float("12.34.56")

# Empty sequence
empty_list = []
value = max(empty_list)

6. IndexError

my_list = [1, 2, 3]
print(my_list[5])  # Index out of range

empty_list = []
print(empty_list[0])  # No elements

7. KeyError

my_dict = {"name": "John", "age": 25}
print(my_dict["address"])  # Key doesn't exist

empty_dict = {}
print(empty_dict["any_key"])

8. ZeroDivisionError

result = 10 / 0

numbers = [1, 0, 2]
for num in numbers:
    print(5 / num)  # Will fail when num is 0

9. FileNotFoundError

with open("non_existent_file.txt", "r") as file:
    content = file.read()

import os
os.remove("file_that_doesnt_exist.txt")

10. PermissionError

# Try to write to a read-only file (create a read-only file first)
with open("read_only_file.txt", "w") as file:
    file.write("test")

11. ImportError

import non_existent_module

from math import non_existent_function

12. AttributeError

x = 5
x.append(10)  # Integer has no append method

class MyClass:
    pass

obj = MyClass()
obj.undefined_method()

13. RuntimeError

# Custom runtime error
def problematic_function():
    raise RuntimeError("Something went wrong!")

problematic_function()

14. RecursionError

def infinite_recursion():
    return infinite_recursion()

infinite_recursion()  # Maximum recursion depth exceeded

15. KeyboardInterrupt

# Run this and press Ctrl+C
try:
    while True:
        pass
except KeyboardInterrupt:
    print("Program interrupted by user!")

16. MemoryError

# This may cause MemoryError on systems with limited memory
try:
    huge_list = [0] * (10**10)
except MemoryError:
    print("Out of memory!")

17. OverflowError

import math
try:
    result = math.exp(1000)  # Too large for float
except OverflowError:
    print("Number too large!")

18. StopIteration

iterator = iter([1, 2])
print(next(iterator))  # 1
print(next(iterator))  # 2
print(next(iterator))  # Raises StopIteration

19. AssertionError

x = 5
assert x == 10, "x should be 10"  # Assertion fails

def divide(a, b):
    assert b != 0, "Cannot divide by zero"
    return a / b

divide(10, 0)

20. UnboundLocalError

x = 10

def my_function():
    print(x)  # This would work
    x = 5     # But this makes x local

my_function()  # UnboundLocalError

21. ModuleNotFoundError

try:
    import non_existent_package
except ModuleNotFoundError as e:
    print(f"Module not found: {e}")

22. TimeoutError

import socket
socket.setdefaulttimeout(0.0001)
try:
    socket.getaddrinfo("example.com", 80)
except TimeoutError:
    print("Connection timed out")

23. NotImplementedError

class AbstractClass:
    def must_implement(self):
        raise NotImplementedError("Subclasses must implement this method")

class ConcreteClass(AbstractClass):
    pass  # Forgot to implement the method

obj = ConcreteClass()
obj.must_implement()

24. Complete Example with Multiple Exceptions

def demonstrate_exceptions():
    exceptions = [
        ("NameError", lambda: print(undefined_var)),
        ("TypeError", lambda: "5" + 3),
        ("IndexError", lambda: [1, 2, 3][10]),
        ("KeyError", lambda: {"a": 1}["b"]),
        ("ZeroDivisionError", lambda: 10 / 0),
        ("ValueError", lambda: int("abc")),
    ]

    for name, func in exceptions:
        try:
            func()
        except Exception as e:
            print(f"{name}: {type(e).__name__} - {e}")

demonstrate_exceptions()

25. Custom Exception

class CustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

def validate_age(age):
    if age < 0:
        raise CustomError("Age cannot be negative!")
    if age > 150:
        raise CustomError("Age seems unrealistic!")
    return True

try:
    validate_age(-5)
except CustomError as e:
    print(f"Custom error: {e}")

26. Multiple Exception Handling

def handle_multiple_errors():
    try:
        # This will cause different errors based on input
        num = int(input("Enter a number: "))
        result = 100 / num
        print(f"100 divided by {num} is {result}")

    except ValueError:
        print("Please enter a valid integer!")
    except ZeroDivisionError:
        print("Cannot divide by zero!")
    except Exception as e:
        print(f"Unexpected error: {e}")

handle_multiple_errors()

These examples demonstrate the most common exceptions you’ll encounter in Python programming. Each exception serves as a specific signal about what went wrong in your code.

Similar Posts

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

  •  List Comprehensions 

    List Comprehensions in Python (Basic) with Examples List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops. Basic Syntax: python [expression for item in iterable if condition] Example 1: Simple List Comprehension Create a list of squares from 0 to 9. Using Loop: python…

  • Python and PyCharm Installation on Windows: Complete Beginner’s Guide 2025

    Installing Python and PyCharm on Windows is a straightforward process. Below are the prerequisites and step-by-step instructions for installation. Prerequisites for Installing Python and PyCharm on Windows Step-by-Step Guide to Install Python on Windows Step 1: Download Python Step 2: Run the Python Installer Step 3: Verify Python Installation If Python is installed correctly, it…

  • What is list

    In Python, a list is a built-in data structure that represents an ordered, mutable (changeable), and heterogeneous (can contain different data types) collection of elements. Lists are one of the most commonly used data structures in Python due to their flexibility and dynamic nature. Definition of a List in Python: Example: python my_list = [1, “hello”, 3.14,…

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

Leave a Reply

Your email address will not be published. Required fields are marked *