DEV Community

qing
qing

Posted on

Python Error Handling: 10 Patterns Every Developer Should Know

Python Error Handling: 10 Patterns Every Developer Should Know

Error handling is crucial for writing robust Python code. Here are 10 essential patterns.

1. Basic Try/Except

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
    result = 0
Enter fullscreen mode Exit fullscreen mode

2. Multiple Exceptions

try:
    data = int(input("Enter number: "))
except (ValueError, TypeError) as e:
    print(f"Invalid input: {e}")
Enter fullscreen mode Exit fullscreen mode

3. Finally Block

file = None
try:
    file = open("data.txt")
    content = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    if file:
        file.close()
Enter fullscreen mode Exit fullscreen mode

4. Context Manager (Recommended)

# Better approach using with statement
with open("data.txt") as file:
    content = file.read()
# File automatically closed
Enter fullscreen mode Exit fullscreen mode

5. Custom Exceptions

class ValidationError(ValueError):
    def __init__(self, field, message):
        self.field = field
        super().__init__(f"{field}: {message}")

def validate_age(age):
    if not 0 <= age <= 150:
        raise ValidationError("age", f"Invalid: {age}")
Enter fullscreen mode Exit fullscreen mode

6. Exception Chaining

try:
    config = json.load(open("config.json"))
except json.JSONDecodeError as e:
    raise RuntimeError("Config file is corrupted") from e
Enter fullscreen mode Exit fullscreen mode

7. Suppress Specific Exceptions

from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove("temp_file.txt")
# No error if file doesn't exist
Enter fullscreen mode Exit fullscreen mode

8. Logging Exceptions

import logging

logging.basicConfig(level=logging.ERROR)

try:
    risky_operation()
except Exception as e:
    logging.error(f"Operation failed: {e}", exc_info=True)
Enter fullscreen mode Exit fullscreen mode

9. Retry Pattern

import time

def retry(func, max_attempts=3, delay=1):
    for attempt in range(max_attempts):
        try:
            return func()
        except Exception as e:
            if attempt == max_attempts - 1:
                raise
            time.sleep(delay * (attempt + 1))
Enter fullscreen mode Exit fullscreen mode

10. Result Pattern (No Exceptions)

from dataclasses import dataclass
from typing import Optional

@dataclass
class Result:
    success: bool
    value: Optional[any] = None
    error: Optional[str] = None

def safe_divide(a, b) -> Result:
    if b == 0:
        return Result(False, error="Division by zero")
    return Result(True, value=a/b)
Enter fullscreen mode Exit fullscreen mode

Summary

Master these patterns and your Python code will be significantly more robust!


Follow me for more Python tips! ๐Ÿ

Follow for more Python content!


๐Ÿ’ก Related: **Content Creator Ultimate Bundle (Save 33%)* โ€” $30*

Top comments (0)