Examples of Python Exceptions

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

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.sub()

    Python re.sub() Method Explained The re.sub() method is used for searching and replacing text patterns in strings. It’s one of the most powerful regex methods for text processing. Syntax python re.sub(pattern, repl, string, count=0, flags=0) Example 1: Basic Text Replacement python import re text = “The color of the sky is blue. My favorite color is blue too.” #…

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

  • Class Variables Andmethds

    Class Variables Class variables are variables that are shared by all instances of a class. They are defined directly within the class but outside of any method. Unlike instance variables, which are unique to each object, a single copy of a class variable is shared among all objects of that class. They are useful for…

  • 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…

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • AttributeError: ‘NoneType’ Error in Python re

    AttributeError: ‘NoneType’ Error in Python re This error occurs when you try to call match object methods on None instead of an actual match object. It’s one of the most common errors when working with Python’s regex module. Why This Happens: The re.search(), re.match(), and re.fullmatch() functions return: When you try to call methods like .group(), .start(), or .span() on None, you get this error. Example That Causes…

Leave a Reply

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