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

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

  • Python Calendar Module

    Python Calendar Module The calendar module in Python provides functions for working with calendars, including generating calendar data for specific months or years, determining weekdays, and performing various calendar-related operations. Importing the Module python import calendar Key Methods in the Calendar Module 1. calendar.month(year, month, w=2, l=1) Returns a multiline string with a calendar for the specified month….

  • The Fractions module

    The Fractions module in Python is a built-in module that provides support for rational number arithmetic. It allows you to work with fractions (like 1/2, 3/4, etc.) exactly, without the precision issues that can occur with floating-point numbers. What Problems Does It Solve? Problem with Floating-Point Numbers: python # Floating-point precision issue print(0.1 + 0.2) # Output:…

  • Challenge Summary: Inheritance – Polygon and Triangle Classes

    Challenge Summary: Inheritance – Polygon and Triangle Classes Objective: Create two classes where Triangle inherits from Polygon and calculates area using Heron’s formula. 1. Polygon Class (Base Class) Properties: Methods: __init__(self, num_sides, *sides) python class Polygon: def __init__(self, num_sides, *sides): self.number_of_sides = num_sides self.sides = list(sides) 2. Triangle Class (Derived Class) Inheritance: Methods: __init__(self, *sides) area(self) python import math…

  • What is general-purpose programming language

    A general-purpose programming language is a language designed to be used for a wide variety of tasks and applications, rather than being specialized for a particular domain. They are versatile tools that can be used to build anything from web applications and mobile apps to desktop software, games, and even operating systems. Here’s a breakdown…

  • positive lookbehind assertion

    A positive lookbehind assertion in Python’s re module is a zero-width assertion that checks if the pattern that precedes it is present, without including that pattern in the overall match. It’s the opposite of a lookahead. It is written as (?<=…). The key constraint for lookbehind assertions in Python is that the pattern inside the…

Leave a Reply

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