Common error handling techniques in Python, with examples and outputs.
- Basic try-except blocks
- Handling multiple exceptions
- Using exception objects
- Try-except-else-finally structure
- Raising exceptions
- Creating and using custom exceptions
- Re-raising exceptions
- Using assert statements
- Context managers for resource handling
1. Basic Try-Except Block
# Basic try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")
# Output: Error: Division by zero!
# Handling multiple exceptions
try:
value = int("abc")
except ValueError:
print("Error: Invalid integer!")
except ZeroDivisionError:
print("Error: Division by zero!")
# Output: Error: Invalid integer!
2. Using Exception as an Object
try:
file = open("nonexistent_file.txt", "r")
except FileNotFoundError as e:
print(f"Error: {e}")
print(f"Error type: {type(e).__name__}")
# Output:
# Error: [Errno 2] No such file or directory: 'nonexistent_file.txt'
# Error type: FileNotFoundError
3. Try-Except-Else-Finally
try:
x = 1
y = 2
result = x + y
except TypeError:
print("Error: Type mismatch!")
else:
print(f"The result is: {result}")
finally:
print("This always executes")
# Output:
# The result is: 3
# This always executes
# Example with an exception
try:
x = "1"
y = 2
result = x + y
except TypeError:
print("Error: Type mismatch!")
else:
print(f"The result is: {result}")
finally:
print("This always executes")
# Output:
# Error: Type mismatch!
# This always executes
4. Raising Exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 120:
raise ValueError("Age is too high")
return f"Age {age} is valid"
try:
print(validate_age(25))
print(validate_age(-5))
except ValueError as e:
print(f"Validation Error: {e}")
# Output:
# Age 25 is valid
# Validation Error: Age cannot be negative
5. Custom Exceptions
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def raise_custom_error(value):
if value < 0:
raise CustomError("Value cannot be negative")
try:
raise_custom_error(-5)
except CustomError as e:
print(f"Custom Error: {e}")
# Output: Custom Error: Value cannot be negative
6. Handling and Re-raising Exceptions
def process_data(data):
try:
return int(data)
except ValueError:
print("Invalid data. Re-raising the exception.")
raise
try:
result = process_data("abc")
except ValueError:
print("Caught re-raised exception in outer block")
# Output:
# Invalid data. Re-raising the exception.
# Caught re-raised exception in outer block
7. Using assert Statements
def calculate_average(numbers):
assert len(numbers) > 0, "List cannot be empty"
return sum(numbers) / len(numbers)
try:
print(calculate_average([1, 2, 3, 4, 5]))
print(calculate_average([]))
except AssertionError as e:
print(f"Assertion Error: {e}")
# Output:
# 3.0
# Assertion Error: List cannot be empty
8. Context Managers for Resource Handling
class FileManager:
def __init__(self, filename):
self.filename = filename
self.file = None
def __enter__(self):
self.file = open(self.filename, 'w')
return self.file
def __exit__(self, exc_type, exc_value, traceback):
if self.file:
self.file.close()
if exc_type is not None:
print(f"An error occurred: {exc_value}")
return True # Suppress any exception
with FileManager('test.txt') as f:
f.write("Hello, World!")
raise ValueError("Simulated error")
print("Execution continues after the context manager")
# Output:
# An error occurred: Simulated error
# Execution continues after the context manager