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.